我尝试在不递归的情况下打印反向链接列表并反向链接列表。我怎样才能做到这一点?
问题:如何在不使用递归且不反转列表的情况下打印反向链接列表?
要求:没有多余的空间,不能反向链接列表,不能使用递归。
这是链表节点的定义
class Node {
int value;
Node next;
public Node(int val) {
this.value = val;
}
}
这是我的printReverseLinkedList的递归版本:
public void printReverseList(Node head) {
Node temp = head;
if (temp.next != null) {
printReverseList(temp.next);
}
System.out.print(temp.value);
}
Performace无关紧要,因为我只想以这种方式做。
如果您既不可以反转列表,也不可以使用递归,那么执行此操作的唯一方法是:
public void printReversList(Node head) {
Node current = head; // used to search through the list
Node last = null; // stores the last element that we printed
while (last != head) { // = we didn't print everything yet
// find next element to print - it's one element before we reach "last"
while (current.next != last) {
current = current.next;
}
// Store the current element as the new last and print it
last = current;
system.out.print(last.value);
// reset current and start all over
current = head;
}
}
这是非常无效的,但是我没有其他办法可以想到。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句