【发布时间】:2016-04-17 08:50:27
【问题描述】:
我已经编写了下面的代码来反转链表的前 K 个节点,它在 Reversing first K nodes of Linked List,Why recursion executing twice for last iteration 中解决了一些问题,现在它可以正常工作但是为什么当我尝试使用变量“k”时它会导致链表中的循环而不是“if”条件下的“presentCounter”,是什么原因?以及如何避免?
/*
* Condition K <= Length of linked list.
* node = null
* nextNode headNode of the linked list
*/
public void reverseNode(Node node, Node nextNode, int k) {
int presentCounter = k;
if (k > 1) {
k = k - 1;
this.reverseNode(nextNode, nextNode.next, k);
}
if (presentCounter == 1) {
this.kNode = nextNode.next; // Saving K's Next Node
this.headNode = nextNode; // Setting K node as head node
}
if (node == null) {
nextNode.next = this.kNode;
} else
nextNode.next = node;
}
【问题讨论】:
标签: algorithm sorting recursion data-structures linked-list