有人能提供在Java中反向打印Linkedlist的可能方法吗。我理解的一种方法是递归地到达列表的末尾,然后从后面开始打印,然后递归地到达前面。请分享可能的方法。
我使用的节点具有next和previous。
我想的解决方案如下。但在这里,每次进入递归循环时,我都需要创建一个变量。这很糟糕:(
public void reversePrinting(int count){
if(count==0){ //to assign the root node to current only once
current=root;
count++;
}
else{ //moving current node to subsequent nodes
current=current.nextNode;
}
int x= current.data;
if(current.nextNode==null){
System.out.println(x);
return;
}
reversePrinting(count);
System.out.println(x);
}
试试这个,它可以反向链接列表
public class DoReverse{
private Node head;
private static class Node {
private int value;
private Node next;
Node(int value) {
this.value = value;
}
}
public void addToTheLast(Node node) {
if (head == null) {
head = node;
}
else {
Node temp = head;
while (temp.next != null)
temp = temp.next;
temp.next = node;
}
}
public void printList(Node head) {
Node temp = head;
while (temp != null) {
System.out.format("%d ", temp.value);
temp = temp.next;
}
System.out.println();
}
public static Node reverseList(Node head){
Node prev = null;
Node current = head;
Node next = null;
while(current != null){
next = current.next;
current.next = prev;
prev = current;
current = next;
}
head = prev;
return head;
}
public static void main(String[] args) {
DoReverse list = new DoReverse();
// Creating a linked list
Node head = new Node(5);
list.addToTheLast(head);
list.addToTheLast(new Node(6));
list.addToTheLast(new Node(7));
list.addToTheLast(new Node(1));
list.addToTheLast(new Node(2));
list.addToTheLast(new Node(10));
System.out.println("Before Reversing :");
list.printList(head);
Node reverseHead= list.reverseList(head);
System.out.println("After Reversing :");
list.printList(reverseHead);
}
}
为什么不复制列表以便反转:
用Java递归反转链表
然后像往常一样循环列表的副本?