我尝试打印一个反向链表,没有递归和反向链表。我怎么能这么做?
问题:如何在不使用递归和不反转列表的情况下打印反向链接列表?
Requirements:没有额外的空间,不能反向链接列表,不能使用递归。
下面是链接列表节点的定义
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);
}
性能并不重要,因为我只想这样做.
发布于 2016-06-08 15:44:18
如果您既不能反转列表,也不能使用递归,那么唯一的方法是:
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;
}
}
这是非常无效的,但我没有其他办法可以想到。
发布于 2016-06-08 15:49:18
用一个堆栈然后弹出怎么样?你说过用另一种数据结构就行了。这不是很好的代码,但是,应该完成工作。
public void printReversList(Node head) {
Stack<Node> stack = new Stack<>();
while (head != null){
stack.push(head);
head = head.next;
}
while (!stack.isEmpty()){
System.out.println(stack.pop());
}
}
发布于 2016-06-08 15:42:58
你可以试试这个:
public void printReverseList(Node head) {
if(head == null) return;
Node prev = null;
Node revers = head;
Node nex = null;
while (revers != null){
nex = revers.next;
revers.next = prev;
prev = revers;
revers = nex;
}
System.out.println(prev);
}
https://stackoverflow.com/questions/37706805
复制相似问题