簡體   English   中英

在java中實現鏈表

[英]Implementing Linked List in java

我正在嘗試在 Java 中實現鏈表,但沒有打印出任何內容。 我嘗試調試它,似乎每次調用 Add 函數時,前一個值都會被覆蓋。 但是,當我檢查它的邏輯時,它應該可以工作。

public class MyLinkedList {

public Node head;
public Node curr;

public MyLinkedList() {
    // TODO Auto-generated constructor stub
    head = null;
    curr = null;
}

public void Add(int data) {
    Node box = new Node();
    box.data = data;
    box.next = null;
    curr = head;
    if (curr == null) {
        head = box;
        curr = null;
    }

    else {
        while (curr.next != null) {
            curr = curr.next;

        }
        curr.next = box;
    }
}

public void Print() {
    curr = head;
    while (curr != null) {
        System.out.println(curr.data);
        curr = curr.next;
    }
}
}

這就是 Node 類所具有的

public class Node {
    public int data;
   public Node next;
}

你的代碼沒問題。 去刪除 *.class 文件。 它可能會停留在代碼的早期階段。 *.class 文件位於輸出文件夾下(文件夾的名稱可以根據您使用的 IDE 而改變,但通常在 build 文件夾下。)您可能需要完全刪除該文件夾。

它已經可以工作了,但我會為您整理一下:

public class MyLinkedList {

    private Node head; //never expose a field as public

    //the whole constructor was unnecessary

    public void add(int data) { //methods start with a lower case
        add(new Node(data)); //nodes always need data, so I'm passing in constructor
    }

    // this method adds an existing node rather than the previous add both
    // creating, finding the end and adding
    private void add(Node node) {
        if (head == null) {
            head = node;
        } else {
            lastNode().next = node;
        }
    }

    private Node lastNode() { //finds the last node in the chain
        Node curr = head; //curr is local
        while (curr.next != null) {
            curr = curr.next;
        }
        return curr;
    }

    public void print() { //methods start with a lower case
        Node curr = head; //curr is local
        while (curr != null) {
            System.out.println(curr.data);
            curr = curr.next;
        }
    }

    private static class Node { //this class is just useful internally to MyLinkedList
        private final int data; //final - node data doesn't change
        private Node next;

        private Node(int data) {
            this.data = data;
        }
    }
}

暫無
暫無

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

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