标签:solution 翻转 eve ons example size this out val
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
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
Note:
一个链表中每k个结点翻转,结尾处不满k个的保持原样
1 class Solution { 2 public: 3 ListNode* reverseKGroup(ListNode* head, int k) { 4 if (k == 1)return head; 5 int count = 0; 6 ListNode*hh = NULL, *before = NULL, *p = NULL, *now = NULL; 7 ListNode*end = head; 8 for (int i = 0; i < k-1; i++) 9 if(end) 10 end = end->next; 11 while (head) { 12 count++; 13 if (count == 1 && !end) 14 { 15 if (!hh) 16 hh = head; 17 break; 18 } 19 if (count == k) { 20 if(before) 21 before->next = head; 22 before = now; 23 } 24 if (count == 1) 25 now = head; 26 if (hh == NULL && count == k)hh = head; 27 ListNode*tmp = head->next; 28 head->next = p; 29 p = head; 30 head = tmp; 31 if (count == k) { 32 count = 0; 33 p = NULL; 34 } 35 if(end) 36 end = end->next; 37 } 38 if(before) 39 before->next = head; 40 return hh; 41 } 42 };
我的题解考虑了很多特殊情况,估计有简单得多的解法吧,现在乱七八糟的
19.1.30 [LeetCode 24] Reverse Nodes in k-Group
标签:solution 翻转 eve ons example size this out val
原文地址:https://www.cnblogs.com/yalphait/p/10336935.html