leetcode: Reverse Nodes in k-Group

http://oj.leetcode.com/problems/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

思路

每次拿k个节点倒序,处理好边界条件。

 1 class Solution {
 2 public:
 3     ListNode *reverseKGroup(ListNode *head, int k) {
 4         if (1 == k) {
 5             return head;
 6         }
 7         
 8         ListNode *p = head, *prev = NULL;
 9         
10         while (p != NULL) {
11             ListNode *first_node = p, *kth_node = p;
12             
13             for (int i = 1; i < k; ++i) {
14                 kth_node = kth_node->next;
15                 
16                 if (NULL == kth_node) {
17                     if (prev != NULL) {
18                         prev->next = p;
19                     }
20                     
21                     return head;
22                 }
23             }
24             
25             if (NULL == prev) {
26                 head = kth_node;
27             }
28             
29             p = kth_node->next;
30             
31             ListNode *tmp_head = NULL, *tmp_tail = NULL, *tmp;
32             
33             while (first_node != kth_node) {
34                 tmp = first_node->next;
35                 
36                 if (NULL == tmp_head) {
37                     tmp_head = tmp_tail = first_node;
38                     tmp_tail->next = NULL;
39                 }
40                 else {
41                     first_node->next = tmp_head;
42                     tmp_head = first_node;
43                 }
44                 
45                 first_node = tmp;
46             }
47             
48             kth_node->next = tmp_head;
49             tmp_head = kth_node;
50             
51             if (NULL != prev) {
52                 prev->next = tmp_head;
53             }
54             
55             prev= tmp_tail;
56         }
57         
58         return head;
59     }
60 };
原文地址:https://www.cnblogs.com/panda_lin/p/reverse_nodes_in_k_group.html