簡體   English   中英

Java鏈表添加方法

[英]Java Linked List add Method

我正在嘗試實現一個使用包含頭、尾和當前節點的節點類的鏈表。 鏈表的一部分是一個 add 方法,它應該向鏈表中當前節點的末尾添加一個值,就像實際鏈表一樣。 我的問題是它只適用於第一個節點,然后就停在那里。 例如,在我的 main 中,我嘗試通過調用add(1);測試代碼add(1); add(2); . 控制台顯示我1但僅此而已。 我不確定錯誤是在我的 add 方法、toString 方法還是節點類中。

我還要補充一點,我測試了在任何一種情況下是否將正確的值分配給“當前”,並且確實如此。 這讓我想知道是否是 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;
    }
}

字符串:

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

    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM