1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     ListNode *reverseKGroup(ListNode *head, int k) {
12         if (!head || !head->next) return head;
13         ListNode *result = new ListNode(0);
14         ListNode *old = new ListNode(0);
15         old->next = head;
16         ListNode *runner = head;
17         int len = 1;
18         while (runner->next) {
19             runner = runner->next;
20             len++;
21         }
22         runner = result;
23         for (int i = 0; i < len/k; i++) {
24             for (int j = 0; j < k; j++) {
25                 head = old->next;
26                 old->next = head->next;
27                 head->next = runner->next;
28                 runner->next = head;
29             }
30             while (runner->next) runner = runner->next;
31         }
32         runner->next = old->next;
33         return result->next;
34     }
35 };

 

posted on 2015-03-23 10:08  keepshuatishuati  阅读(105)  评论(0编辑  收藏  举报