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

[解题思路]

[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);
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:            }