Reverse Nodes in k-Group [LeetCode]

时间:2023-09-30 13:10:14

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.

 /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *reverseKGroup(ListNode *head, int k) {
if(k <= )
return head; ListNode *iterate = head;
int num = ;
while(iterate != NULL) {
num ++;
iterate = iterate -> next;
}
if(num < k)
return head; ListNode * new_head = NULL;
ListNode * tail = head;
int count = k;
while(head != NULL && count > ) {
ListNode *pre_head = new_head;
new_head = head;
head = head->next;
count --;
new_head->next = pre_head;
} if(head != NULL)
tail->next = reverseKGroup(head, k); return new_head;
}
};