aboutsummaryrefslogtreecommitdiff
path: root/reverse_node_k.cpp
blob: e57291a6e3a2fd62057360e05c5d4e90f906a9f8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include "leetcode.h"

class Solution {
public:
  ListNode *reverseKGroup(ListNode *head, int k) {
    ListNode *cursor = head;
    for (int i = 0; i < k; i++) {
      if (cursor == nullptr)
        return head;
      cursor = cursor->next;
    }
    ListNode *curr = head;
    ListNode *prev = nullptr;
    ListNode *next = nullptr;
    for (int i = 0; i < k; i++) {
      next = curr->next;
      curr->next = prev;
      prev = curr;
      curr = next;
    }
    head->next = reverseKGroup(curr, k);
    return prev;
  }
};

int main() {}