[英]How to print a reverse linked list without using recursion in Java?
I try printing a reverse linked list without recursion and reversing the linked list.我尝试在没有递归的情况下打印反向链接列表并反转链接列表。 How can I do that?
我该怎么做?
Questions : How to print a reverse linked list without using recursion and not reversing the list?问题:如何在不使用递归和不反转列表的情况下打印反向链接列表?
Requirements : No extra space, cannot reverse a linked list, cannot use recursion.要求:没有多余的空间,不能反转链表,不能使用递归。
Here is the definition of the linked list Node这里是链表Node的定义
class Node {
int value;
Node next;
public Node(int val) {
this.value = val;
}
}
Here is my recursion version of printReverseLinkedList:这是我的 printReverseLinkedList 递归版本:
public void printReverseList(Node head) {
Node temp = head;
if (temp.next != null) {
printReverseList(temp.next);
}
System.out.print(temp.value);
}
Performace does not matter, because I just want to do in this way.性能无所谓,因为我就是想做这种方式。
If you may neither reverse the list, nor use recursion, the only way to do this is this:如果您既不能反转列表,也不能使用递归,那么唯一的方法是:
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;
}
}
It is highly ineffective, but there is no other way I can think of.这是非常无效的,但我想不出其他方法。
How about using a Stack and then poping ?如何使用堆栈然后弹出? You said using another data-structure will be fine.
你说使用另一种数据结构就可以了。 This is not the fine code, but, should get the job done.
这不是很好的代码,但是,应该可以完成工作。
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());
}
}
you can try this:你可以试试这个:
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);
}
void ReversePrint(Node head) {
// This is a "method-only" submission.
// You only need to complete this method.
Stack<Node> stk=new Stack<>();
Node temp=head;
while(temp!=null){
stk.push(temp);
temp=temp.next;
}
while(!stk.isEmpty()){
System.out.println(stk.pop().data);
}
}
public void printReverseList(Node head) {
Node node = head;
List<Integer> list = new ArrayList<Integer>();
if (head == null){
System.out.println(head.data);
}
else{
while (node != null){
list.add(0, node.data);
node = node.next;
}
for (int item:list){
System.out.println(item);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.