025 Reverse Nodes in k-Group[H]

1 題目描述

Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.

k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.

You may not alter the values in the nodes, only nodes itself may be changed.

Only constant memory is allowed.

難度:Hard

2 題目樣例

For example,Given this linked list: 1->2->3->4->5For k = 2, you should return: 2->1->4->3->5For k = 3, you should return: 3->2->1->4->5

3 題意分析

每k個節點翻轉一次,要求是不改變節點的值並且空間複雜度為 O(1)

4 思路分析

整體思路跟之前翻轉2個節點的題是一致的。

每k個節點處理一次即可,不足k個節點的話就不處理(根據樣例)。

那麼題意就轉化為了怎麼翻轉一個長度為k的鏈表了,考慮到空間複雜度為 O(1) ,那麼我們只要把單鏈表中的指針全部反向同時首尾指針交換即可。

代碼如下

class Solution {public: ListNode* reverseK(ListNode* prev, int k){ ListNode* start=prev->next; ListNode* p1; ListNode* p2; ListNode* tp; int len = 0; tp = prev; p1 = prev; p2 = prev->next; while(len<k&&tp){ tp =tp->next; len++; } if(!tp) return NULL; for(int i=0;i<k;i++){ tp = p1; p1 = p2; p2 = p2->next; p1->next = tp; } prev->next->next = p2; prev->next = p1; return start; } ListNode* reverseKGroup(ListNode* head, int k) { ListNode tohead(0); ListNode* tp; tohead.next = head; tp = &tohead; while(tp) tp = reverseK(tp, k); return tohead.next; }};

整體時間複雜度 O(n) ,空間複雜度 O(1)

5 後記

標準的數據結構題。

推薦閱讀:

[leetcode algorithms]題目7
【LeetCode】005-最長迴文子串
Leetcode-Maximum Subarray
[leetcode algorithms]題目16

TAG:LeetCode | 演算法 | 演算法設計 |