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

[leetcode 25] Reverse Nodes in k-Group

2014-12-06 15:13 645 查看
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


[Solution]

每次访问连续的k个节点,将k个节点逆置。

注意首位节点的衔接。

ListNode *reverseKGroup(ListNode *head, int k)
{
if (k <= 1 || head == NULL)
return head;
ListNode *dummy = new ListNode(INT_MIN);
dummy->next = head;
ListNode *p, *q, *tmp_head, *tmp_tail;
int i = 0;

p = dummy;
tmp_head = dummy;
while (p != NULL)
{
if (i == k)
{
q = p->next;
p->next = NULL;
tmp_tail = tmp_head->next;
tmp_head->next = reverse(tmp_head->next);
p = tmp_tail;
p->next = q;
tmp_head = p;
i = 0;
}
else
{
i++;
p = p->next;
}
}

head = dummy->next;
delete dummy;
return head;
}

ListNode *reverse(ListNode *head)
{
ListNode *p = NULL, *q, *r;

q = head;
if (q == NULL)
return NULL;
r = q->next;
while (r != NULL)
{
q->next = p;
p = q;
q = r;
r = r->next;
}
q->next = p;

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