Monday, December 31, 2012

[LeetCode] Reverse Nodes in k-Group 解题报告


Given a linked list, reverse the nodes of a linked list k at a time and return its modified 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.
For example,
Given this linked list: 1->2->3->4->5
For k = 2, you should return: 2->1->4->3->5
For k = 3, you should return: 3->2->1->4->5
» Solve this problem

[解题思路]
同上一题,每K个元素,翻转一次。最后一次如果不到K,再翻转回来即可。代码中链表翻转的code可以拆分成单独函数,这里懒得再refactor了。

[Code]
1:      ListNode *reverseKGroup(ListNode *head, int k) {  
2:      // Start typing your C/C++ solution below  
3:      // DO NOT write int main() function  
4:      ListNode* safeG = new ListNode(-1);  
5:         safeG->next = head;            
6:            if(head == NULL || k==1) return head;  
7:            ListNode* pre = safeG, *cur = head, *post = head->next;  
8:            while(cur!=NULL)  
9:            {  
10:                 post = cur->next;  
11:                 int i =0;  
12:                 while(i<k-1 && post!=NULL)  
13:                 {  
14:                      ListNode *temp = post->next;  
15:                      post->next = cur;  
16:                      cur = post;  
17:                      post = temp;  
18:                      i++;  
19:                 }  
20:                 if(i!=k-1)                 
21:                 {  
22:                      int k =0;  
23:                      ListNode * temp = post;  
24:                      post = cur;  
25:                      cur = temp;  
26:                      while(k<i)  
27:                      {  
28:                           temp = post->next;  
29:                           post->next = cur;  
30:                           cur = post;  
31:                           post = temp;  
32:                           k++;  
33:                      }  
34:                      break;  
35:                 }  
36:                 ListNode* temp = pre->next;  
37:                 pre->next = cur;  
38:                 temp->next = post;  
39:                 pre = temp;  
40:                 cur = pre->next;  
41:            }  
42:            head = safeG->next;  
43:            delete safeG;  
44:            return head;  
45:    }  

No comments:

Post a Comment