Java链表添加方法



我正在尝试实现一个链表,该链表使用包含头、尾和当前节点的节点类。链表的一部分是一个add方法,它应该像实际链表一样,在列表中当前节点的末尾添加一个值。我的问题是,它只适用于第一个节点,然后就停止了。例如,在我的main中,我尝试通过调用add(1);add(2);来测试代码。控制台显示1,但仅此而已。我不确定错误是在我的add方法、toString方法还是节点类中。

我还将补充一点,我测试了在任何一种情况下是否将正确的值分配给了"current",并且确实如此。这让我怀疑toString是否是问题的根源,然而,无论我怎么尝试,我都无法改变它来做出任何改进。

我希望新的眼光能够发现任何可能存在的问题。

添加方法:

public void add(int val){
if(current != null){
Node nextNode = new Node(val, current);
current = nextNode;
tail = nextNode;                    
}
else{
head = tail = new Node(val, null);
current = head;
}
}

节点类别:

public class Node{
public int data;
public Node next;
public Node(int d, Node next) {
this.data = d;
this.next = next;
}
}

toString:

public String toString(){
for(Node x = head; x != null; x = x.next){
System.out.println(x.data);
}

全部:

public class IntLList extends IntList{    
public IntLList(){
}
public class Node{
public int data;
public Node next;
public Node(int d, Node next) {
this.data = d;
this.next = next;
}
}
Node head = null;
Node tail = null;
Node current = null;
public void add(int val){
if(current != null){
Node nextNode = new Node(val, current);
current = nextNode;
tail = nextNode;    
}
else{
head = tail = new Node(val, null);
current = head;        
}
}
public int get(int index){
return 0;
}
public void set(int index, int val){
}
public void remove(int index) throws ArrayIndexOutOfBoundsException{
}
public int size(){
return 0;
}
public String toString(){
for(Node x = head; x != null; x = x.next){
System.out.println(x.data);
}
return "temp";
}
public void removeLast(){
}
public boolean isEmpty(){
boolean isEmpty = false;
if(head == null){       
isEmpty = true;
}
return isEmpty;
}
public void clear(){    
}
public static void main(String[] args) {
IntLList i = new IntLList();
i.add(1);
i.add(2);
i.toString();
}
}

进行以下更改:

public class Node{
public int data;
public Node next;
public Node(int d, Node next) {
this.data = d;
this.next = NULL; // this is to set the next node of current node to null
if(next!=NULL)
next.next=this; // this is to set the previous node to point to current node
}
}

最新更新