下面是我的代碼。我試圖實現鏈接列表。下面是我的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();
}
}
一般評論/警告:Java集合類有一些已經叫做'LinkedList'的東西,所以你可能不應該給你的類同名。 –
@TimBiegeleisen謝謝你指出它。請記住它。請你找到問題。 –
看看我的答案。我爲你的'add()'方法給了你一個完整的實現。 –