Reverse Alternate K Nodes
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 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
|
ListNode* cut(ListNode* A, int k) { ListNode* runner = A; for(int i = 0; i < k and runner->next; i++) runner = runner->next; return runner; } ListNode* reverse(ListNode* node) { ListNode* dummy = new ListNode(-1); ListNode* runner = node; while(runner) { ListNode* nxt = runner->next; runner->next = dummy->next; dummy->next = runner; runner = nxt; } return dummy->next; } ListNode* Solution::solve(ListNode* A, int B) { ListNode* dummy = new ListNode(-1); dummy->next = A; ListNode* tail = dummy; while(tail) { ListNode* half = cut(tail, B); ListNode* safe = half->next; half->next = NULL; ListNode* rev = reverse(tail->next); tail->next = rev; while(tail->next) tail = tail->next; tail->next = safe; for(int i = 0; i < B and tail; i++) tail = tail->next; } return dummy->next; }
|