【发布时间】:2016-07-09 23:59:44
【问题描述】:
我从http://www.geeksforgeeks.org/reverse-alternate-k-nodes-in-a-singly-linked-list/得到了这个问题和Java解决方案
给定一个链表,编写一个函数来反转每个交替的 k 个节点 输入:1->2->3->4->5->6->7->8->9->NULL 和 k = 3 输出:3->2->1->4->5->6->9->8->7->NULL。
在他们的 java 代码中:我真的不明白为什么需要第 2 步)。 除了 kAltReverse(Node node, int k) 中的第一个参数之外,节点没有在其他任何地方使用 方法中的这个节点参数在每次递归中都被分配给一个新的变量 current。然后在每个递归中使用 current、prev、next 变量。
那么为什么需要node.next = current in step2)?
Node kAltReverse(Node node, int k) {
Node current = node;
Node next = null, prev = null;
int count = 0;
/*1) reverse first k nodes of the linked list */
while (current != null && count < k) {
next = current.next;
current.next = prev;
prev = current;
current = next;
count++;
}
/* 2) Now head points to the kth node. So change next
of head to (k+1)th node*/
if (node != null) {
node.next = current; **// why node.next should be moved to current even though node is not impacting on anywhere else in 3), 4)???**
}
/* 3) We do not want to reverse next k nodes. So move the current
pointer to skip next k nodes */
count = 0;
while (count < k - 1 && current != null) {
current = current.next;
count++;
}
/* 4) Recursively call for the list starting from current->next.
And make rest of the list as next of first node */
if (current != null) {
current.next = kAltReverse(current.next, k);
}
/* 5) prev is new head of the input list */
return prev;
}
【问题讨论】:
标签: recursion linked-list