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

LeetCode Reverse Nodes in k-Group

2016-01-08 08:50 561 查看
Description:

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:

一开始还在想有没有什么复杂的优化,最后发现单纯写出来就很好了。

我的写法是最naive的写法,似乎有更好的,等我刷完再慢慢更新哈~~~

public class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
if (head == null)
return head;

int i = 0;

ListNode neoHead = head;
for (i = 1; i < k; i++) {
if (neoHead.next == null)
break;
neoHead = neoHead.next;
}
if (i < k)
return head;

ListNode lastTail = null, currentHead, currentTail, nextHead;
ListNode temp, pre, cur;

while (true) {

if (lastTail == null)
currentHead = head;
else
currentHead = lastTail.next;

currentTail = currentHead;
for (i = 1; i < k; i++) {
if (currentTail.next == null)
break;
currentTail = currentTail.next;
}
if (i < k)
return neoHead;

nextHead = currentTail.next;
currentTail.next = null;

if (lastTail == null)
lastTail = currentHead;
else {
lastTail.next = currentTail;
lastTail = currentHead;
}

temp = currentHead.next;
pre = currentHead;
cur = currentHead;
while (temp != null) {
cur = temp;
temp = temp.next;
cur.next = pre;
pre = cur;
}

currentHead.next = nextHead;

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