LeetCode 25. Reverse Nodes in k-Group

#include <iostream>
#include <vector>
using namespace std;

struct ListNode {
  int val;
  ListNode* next;
  ListNode(int x) : val(x), next(NULL) {}
};

// set up a linked list and then reverse it in K-length group.
ListNode* setUpLinkList() {
  ListNode* newHead = new ListNode(0);
  ListNode* current = newHead;
  for(int i = 1; i < 6; ++i) {
    ListNode* tmp = new ListNode(i);
    current->next = tmp;
    current = tmp;
  }
  return newHead;
}

void printList(ListNode* head) {
  ListNode* tmp = head;
  while(tmp) {
    cout << tmp->val << " ";
    tmp = tmp->next;
  }
  cout << endl;
}
ListNode* reverse(ListNode* prev, ListNode* end) {
  ListNode* last = prev->next;
  ListNode* curr = last->next;
  while(curr != end) {
    last->next = curr->next;
    curr->next = prev->next;
    prev->next = curr;

    curr = last->next;
  }
  return last;
}

// reverse the linklist in 3-length.
ListNode* reverseKLength(ListNode* head, int k) {
  ListNode* dummy = new ListNode(0);
  dummy->next = head;
  int count = 0;
  ListNode* prev = dummy;
  while(head) {
    count++;
    if(count % k == 0) {
      prev = reverse(prev, head->next);
      head = prev->next;
    } else {
      head = head->next;
    }
  }
  return dummy->next;
}


int main(void) {
  ListNode* head = setUpLinkList();
  printList(head);
  ListNode* tmp = reverseKLength(head, 3);
  printList(tmp);
}
 

你可能感兴趣的:(LeetCode 25. Reverse Nodes in k-Group)