2015-11-03 60 views
-1

有人可以提供可能的方式在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); 
    } 
+1

我建議你分享你的代碼,並詢問在修復它的具體幫助... – Codebender

+1

難以幫助,沒有看到什麼代碼不適合你... –

回答

0

試試這個,它是能夠扭轉鏈表

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); 


     } 
}