Reverse Nodes in k-Group

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.

样例

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

 

 

嗯。。最近在刷lintcode上的题。然后做到这道题,难度标的是困难但是挺简单的嘛。想到好久没发随笔了就发一个把。

用C++写的,代码如下喽。思路就是一个指针先往前k个然后将两个指针之间的用头插法倒置就好。因为没有说有头结点,所以p == head时要特殊处理。

 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     /**
12      * @param head a ListNode
13      * @param k an integer
14      * @return a ListNode
15      */
16     ListNode *reverseKGroup(ListNode *head, int k) {
17         // Write your code here
18         if(k <= 1 || head == NULL) return head;
19         ListNode *p, *p1, *pre, *pre1, *t;
20         p = head;
21         p1 = head;
22         while(p != NULL) {
23             int flag = 0;
24             for(int i=0;i<k;i++) {
25                 p1 = p1->next;
26                 if(p1 == NULL && i < k-1) {
27                     flag = 1;
28                     break;
29                 }
30             }
31             if(flag) break;
32             
33             pre1 = p;
34             if(p == head) {
35                 head = p1;
36                 while(p != p1) {
37                     t = head;
38                     head = p;
39                     p = p->next;
40                     head->next = t;
41                 }
42             }else {
43                 pre->next = p1;
44                 while(p != p1){
45                     t = pre->next;
46                     pre->next = p;
47                     p = p->next;
48                     pre->next->next = t;
49                 }
50             }
51             pre = pre1;
52         }
53         return head;
54     }
55 };
View Code

 

posted @ 2015-11-20 21:29  -.-|  阅读(144)  评论(0编辑  收藏  举报