Reverse Nodes in k-Group [LeetCode]
Problem Description: http://oj.leetcode.com/problems/reverse-nodes-in-k-group/
Basic Idea: Do it like reverse a linked list with a counter started by k. Record the tail at the first, then let the tail-> next be the head of rest linked list. This is the recursive version, which is much easier than interative version.
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) { 13 if(k <= 1) 14 return head; 15 16 ListNode *iterate = head; 17 int num = 0; 18 while(iterate != NULL) { 19 num ++; 20 iterate = iterate -> next; 21 } 22 if(num < k) 23 return head; 24 25 ListNode * new_head = NULL; 26 ListNode * tail = head; 27 int count = k; 28 while(head != NULL && count > 0) { 29 ListNode *pre_head = new_head; 30 new_head = head; 31 head = head->next; 32 count --; 33 new_head->next = pre_head; 34 } 35 36 if(head != NULL) 37 tail->next = reverseKGroup(head, k); 38 39 return new_head; 40 } 41 };