zoukankan      html  css  js  c++  java
  • 19.1.30 [LeetCode 25] 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

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

  • 相关阅读:
    团队第十天成果及燃尽图。
    团队第九天成果。
    团队第八天成果。
    各组建议。
    团队任务,团队报告。
    团队第六,七天成果。
    团队第五天成果
    最大连续子数组和(简单一维dp)
    小白鼠问题(海明码)
    JUnit练习
  • 原文地址:https://www.cnblogs.com/yalphait/p/10336935.html
Copyright © 2011-2022 走看看