【链表】K个一组翻转链表

题目:

给你一个链表,每 k 个节点一组进行翻转,请你返回翻转后的链表。

k 是一个正整数,它的值小于或等于链表的长度。

如果节点总数不是 k 的整数倍,那么请将最后剩余的节点保持原有顺序。

 

示例:

给你这个链表:1->2->3->4->5

当 k = 2 时,应当返回: 2->1->4->3->5

当 k = 3 时,应当返回: 3->2->1->4->5

 

说明:

你的算法只能使用常数的额外空间。
你不能只是单纯的改变节点内部的值,而是需要实际进行节点交换。

解答:

 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     {
13         if (NULL == head || k <=  1)
14         {
15             return head;
16         }
17 
18         ListNode *dummy = new ListNode(0);
19         dummy->next = head;
20         ListNode *pre = dummy;
21 
22         int i = 0;
23         while (head)
24         {
25             i++;
26             if (i % k == 0)
27             {
28                 pre = reverse(pre, head->next);
29                 head = pre->next;
30             }
31             else
32             {
33                 head = head->next;
34             }
35         }
36         return dummy->next;
37     }
38 
39 
40     ListNode* reverse(ListNode* pre, ListNode *next) 
41     {
42        ListNode *last = pre->next;
43        ListNode *cur = last->next;
44        while (cur != next)
45        {
46            last->next = cur->next;
47            cur->next = pre->next;
48            pre->next = cur;
49 
50            cur = last->next; 
51        }
52        return last;
53     }
54 };

猜你喜欢

转载自www.cnblogs.com/ocpc/p/12815120.html
今日推荐