您的位置:首页 > Web前端 > Node.js

Reverse Nodes in k-Group [LeetCode]

2013-10-17 14:11 204 查看
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 <= 1)
return head;

ListNode *iterate = head;
int num = 0;
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 > 0) {
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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: