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

思路:

类似Reverse Linked List II

代码:

 1     ListNode *reverseKGroup(ListNode *head, int k) {
 2         // IMPORTANT: Please reset any member data you declared, as
 3         // the same Solution instance will be reused for each test case.
 4         if(head == NULL || k <= 1)
 5             return head;
 6         ListNode *pre, *begin, *end, *post, *tmp, *result = NULL, *last, *nextp;
 7         int n;
 8         pre = NULL;
 9         tmp = head;
10         while(tmp){
11             n = 0;
12             begin = tmp;
13             while(tmp){
14                 n++;
15                 if(n == k)
16                     break;
17                 tmp = tmp->next;
18             }
19             if(tmp == NULL)
20                 break;
21             end = tmp;
22             post = end->next;
23             if(pre == NULL)
24                 result = end;
25             else
26                 pre->next = end;
27             last = begin;
28             tmp = begin->next;
29             while(tmp != post){
30                 nextp = tmp->next;
31                 tmp->next = last;
32                 last = tmp;
33                 tmp = nextp;
34             }
35             begin->next = post;
36             tmp = post;
37             pre = begin;
38         }
39         if(result)
40             return result;
41         return head;
42     }
原文地址:https://www.cnblogs.com/waruzhi/p/3418381.html