19.1.30 [LeetCode 24] Reverse Nodes in k-Group

Posted TobicYAL

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了19.1.30 [LeetCode 24] 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.

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:

  • Only constant extra memory is allowed.
  • You may not alter the values in the list‘s nodes, only nodes itself may be changed.

题意

一个链表中每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 };
View Code

我的题解考虑了很多特殊情况,估计有简单得多的解法吧,现在乱七八糟的

以上是关于19.1.30 [LeetCode 24] Reverse Nodes in k-Group的主要内容,如果未能解决你的问题,请参考以下文章

19.1.30 [LeetCode 30] Substring with Concatenation of All Words

Leetcode基础习题集

leetcode-11:1814. 统计一个数组中好对子的数目

leetcode-11:1814. 统计一个数组中好对子的数目

leetcode-11:1814. 统计一个数组中好对子的数目

Leetcode 1814. Count Nice Pairs in an Array