下面是我的代码。我正在尝试实现Linked List.Below是我的3个类.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();
}
}
答案 0 :(得分:4)
添加第一个节点时,不得执行其余逻辑:
if(head==null)
{
head=temp;
return; // add this
}
目前,在添加第一个节点时,您将添加相同的Node
两次,将其链接到自身,从而创建无限列表:
1 -> 1 -> 1 -> ...
答案 1 :(得分: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;
}