2016-06-30 51 views
0

下面是我的代碼。我試圖實現鏈接列表。下面是我的3 classes.Node.java LinkedList.java和Main類。我的代碼被絞死。我試圖調試但沒有找到確切的問題。就我所見,add方法本身存在一些問題。請幫助。沒有通過鏈接列表得到所需的輸出

package com.vikash.LinkedList; 

public class Node { 

    private Object data; 
    private Node next; 

    public Node(Object data) 
    { 
     this.data=data; 
    } 

    public Object getData() { 
     return data; 
    } 
    public void setData(Object data) { 
     this.data = data; 
    } 
    public Node getNext() { 
     return next; 
    } 
    public void setNext(Node next) { 
     this.next = next; 
    } 
} 


package com.vikash.LinkedList; 

public class LinkedList { 

    public Node head; 

    public void add(Object data) 
    { 
     Node temp=new Node(data); 

     if(head==null) 
     { 
      head=temp; 

     } 

     Node current=head; 

     while(current.getNext()!=null) 
     { 
      current=current.getNext(); 
     } 
     current.setNext(temp); 
    } 

    public void add(Object data,int index) 
    { 

    } 

    public int get(int index) 
    { 
     return 0; 
    } 

    public boolean remove(int index) 
    { 
     return false; 
    } 

    public void print() 
    { 
     Node current=head; 
     System.out.println(current.getData()); 
     while(current!=null) 
     { 
      System.out.print(current.getData()); 
      System.out.print("->"); 
      current=current.getNext(); 
     } 
     System.out.println("X"); 
    } 
} 

package com.vikash.LinkedList; 

public class LinkedListTest { 

    public static void main(String[] args) { 

     LinkedList linkedList=new LinkedList(); 
     linkedList.add(1); 
     linkedList.add(2); 
     linkedList.add(3); 
     linkedList.add(4); 

     linkedList.print(); 
    } 
} 
+2

一般評論/警告:Java集合類有一些已經叫做'LinkedList'的東西,所以你可能不應該給你的類同名。 –

+0

@TimBiegeleisen謝謝你指出它。請記住它。請你找到問題。 –

+0

看看我的答案。我爲你的'add()'方法給了你一個完整的實現。 –

回答

4

當您添加的第一個節點,你不能執行邏輯的其餘部分:

if(head==null) 
    { 
     head=temp; 
     return; // add this 
    } 

目前,添加的第一個節點時,要添加相同Node兩次,將其鏈接到本身,從而創造一個無限列表:

1 -> 1 -> 1 -> ... 
+0

@TimBiegeleisen如? – Eran

0

這是你com.vikash.LinkedList.add()方法的實現。我還注意到你的其他幾種方法都沒有實現,或者可能有問題。但是由於你的直接失敗似乎來自於add()方法,希望這會讓你走上正軌。

public void add(Object data) { 
    Node temp = new Node(data); 
    Node curr = head; 

    if (curr == null) { 
     // if the list be empty, assign the head 
     head = temp; 
    } 
    else { 
     // otherwise walk down the list until hitting the end 
     while (curr.getNext() != null) { 
      curr = curr.getNext(); 
     } 

     // and the insert the new node 
     curr.setNext(temp); 
    } 

    return; 
}