zoukankan      html  css  js  c++  java
  • [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.

    You may not alter the values in the nodes, only nodes itself may be changed.

    Only constant memory is allowed.

    For 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

     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         if(k<2) return head;
    13         ListNode *dummy = new ListNode(0);
    14         dummy->next = head;
    15         ListNode *p = dummy;
    16         while(p->next && p->next->next) {
    17             ListNode *prev = p->next, *cur = prev->next;
    18             int i=0;
    19             while(cur && i<k-1) {
    20                 ListNode *temp = cur->next;
    21                 cur->next = prev;
    22                 prev = cur;
    23                 cur = temp;
    24                 i++;
    25             }
    26             
    27             if(i==k-1) {    // k nodes reversed
    28                 ListNode *temp = p->next;
    29                 p->next->next = cur;
    30                 p->next = prev;
    31                 p = temp;
    32             }
    33             else {  // less than k nodes reversed before reach end
    34                 cur = prev->next;
    35                 prev->next = NULL;
    36                 while(cur != p->next) {
    37                     ListNode *temp = cur->next;
    38                     cur->next = prev;
    39                     prev = cur;
    40                     cur = temp;
    41                 }
    42                 break; 
    43             }
    44         }
    45         return dummy->next;
    46     }
    47 };
  • 相关阅读:
    Codeforces 912 D. Fishes (贪心、bfs)
    Codeforces 908 D.New Year and Arbitrary Arrangement (概率&期望DP)
    HDU
    HDU
    POJ-2299 Ultra-QuickSort (树状数组)
    deque!
    HDU
    乘法逆元
    Codeforces 911D. Inversion Counting (数学、思维)
    Codeforces 909E. Coprocessor (拓扑、模拟)
  • 原文地址:https://www.cnblogs.com/amadis/p/6654274.html
Copyright © 2011-2022 走看看