2016-02-28 24 views
0

問題是,在倒轉的方法程序從不顯示第一個數字。例如,如果要倒轉的數字是1 2 3 4,則輸出是.不存在4並且0不應該在那裏。請幫忙。如何做一個反向鏈表

import java.util.Scanner; 


public class LinkTest 
{ 
    public static void main(String [] args) 
    { 
     ListNode head = new ListNode(); 
     ListNode tail = head; 
     int x; 
     head.link = null; 

     Scanner keyboard = new Scanner(System.in); 

     System.out.println("Enter a list of integers ending in zero."); 

     x = keyboard.nextInt(); 

     while(x != 0) 
     { 

      ListNode newOne = new ListNode(); 
      newOne.data = x; 
      newOne.link = null; 
      tail.link = newOne; 
      tail = newOne; 
      x = keyboard.nextInt(); 
     } 

      printLinked(head); 

      delRep(head); 

      invert(head); 

    } 

    public static void printLinked(ListNode cursor) 
    { 

     while(cursor.link != null) 
    { 

     System.out.print(cursor.link.data + " "); 
     cursor = cursor.link; 
    } 

    System.out.println(); 
    } 

    public static void delRep(ListNode num) 
    { 

     ListNode current = num.link; 
     ListNode cursor = null; 
     ListNode duplicate = null; 

    while(current != null && current.link != null) 
    { 
     cursor = current; 

     while(cursor.link != null) 
     { 
      if(current.data == cursor.link.data) 
      { 
       duplicate = cursor.link; 
       cursor.link = cursor.link.link; 
      } 
      else 
      { 
       cursor = cursor.link; 
      } 
     } 

     current = current.link; 
    } 


    System.out.println("Here is the list without repeated "); 
    printLinked(num); 


    } 

public static void invert(ListNode head) 
{ 
    ListNode previous = null; 
    ListNode current = head; 
    ListNode forward; 

    while (current != null) 
    { 
     forward = current.link; 
     current.link = previous; 
     previous = current; 
     current = forward; 
    } 

     System.out.println("Here is the inverted list."); 
     printLinked(previous); 

    } 
} 
+0

你有過在你的IDE調試器的代碼臺階?如果沒有,從那裏開始。 99%的時間可以幫助您快速找到問題。如果您不知道如何使用Google查找使用調試器的信息,請儘快完成此操作。在IDE中進行調試是您現在必須獲得的基本技能。 –

+0

先在紙上做程序。 –

回答

0

你的問題是你的鏈表的head是一個虛擬的。對於輸入1 2 3 4創建此:

0-> 1-> 2-> 3-> 4

在打印時,跳過第一個節點。

invert方法不會將頭部視爲假人。它恢復列表這樣:

4-> 3-> 2-> 1-> 0

然後,由於印刷方法跳過頭,你會得到輸出3 2 1 0

這裏的修復:

public static void invert(ListNode head) 
{ 
    ListNode previous = null; 
    ListNode current = head.link; 
    ListNode forward; 

    while (current != null) 
    { 
     forward = current.link; 
     current.link = previous; 
     previous = current; 
     current = forward; 
    } 

    System.out.println("Here is the inverted list."); 
    head.link = previous; 
    printLinked(head); 
} 
+0

非常感謝。我一直堅持這一點。我沒有想到要查看打印方法,因爲我的delRep工作正常,所以我認爲這不是問題。也謝謝你解釋它,而不僅僅是給我解決方案。這幫了很多。 – rumbledamage