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

Leetcode: Reverse Nodes in k-Group

2014-02-04 22:47 429 查看
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.

If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.

You may not alter the values in the nodes, only nodes itself may be changed.

Only constant memory is allowed.

For example,

Given this linked list: 
1->2->3->4->5


For k = 2, you should return: 
2->1->4->3->5


For k = 3, you should return: 
3->2->1->4->5

比较简单,写了半个多小时,在面试中是不可接受的。应该把reverse单独抽出来做一个函数,这样可以简化逻辑,加快切题速度。

/**
* 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 (head == NULL || k == 1) {
return head;
}

ListNode *tmp = NULL, *last = NULL, *prev = NULL;
ListNode *cur = head;
ListNode *dummy = new ListNode(-1);
head = dummy;
while (cur != NULL) {
last = cur;
int count = 0;
while (count < k - 1 && cur != NULL) {
cur = cur->next;
++count;
}
if (cur == NULL) {
head->next = last;
break;
}

++count;
cur = last;
while (count-- > 0 && cur != NULL) {
tmp = cur->next;
cur->next = prev;
prev = cur;
cur = tmp;
}
head->next = prev;
head = last;
prev = NULL;
}

head = dummy->next;
delete dummy;

return head;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode