用Java创建链接列表

时间:2014-01-07 02:12:08

标签: java linked-list

我对Java很陌生,我想测试一些数据结构,所以我创建了一个真正的BASIC链表,但又添加了一堆节点。

这是我的节点类:

public class LinkedListNode {
    public LinkedListNode next;
    int data;


    // constructor
    LinkedListNode(int newData) {
        this.data = newData;
    }

    public void addNode(LinkedListNode root, LinkedListNode node) {
        if (root.next == null) {
            root.next = node;
        }
        else {
            addNode(root.next, node);
        }
    }
}

以下是我创建节点的方法:

LinkedListNode root = new LinkedListNode(4);    // root
LinkedListNode a = new LinkedListNode(16);
LinkedListNode b = new LinkedListNode(8);
LinkedListNode c = new LinkedListNode(23);
LinkedListNode d = new LinkedListNode(99);
LinkedListNode e = new LinkedListNode(1);
LinkedListNode f = new LinkedListNode(2);
LinkedListNode g = new LinkedListNode(5);
LinkedListNode h = new LinkedListNode(12);

我想使用addNode方法将节点添加到一起,但我在eclipse中收到此错误:

root.addNode(root,b);

Multiple markers at this line
- Syntax error on token ")", delete this 
 token
- Syntax error on token "(", delete this 
 token

我想知道是否有人可以帮我解决这个问题。如果其他人有另一种创建链表的方法,我很乐意阅读它!

我还尝试将addNode方法移到我的LinkedListNode类之外并使用

addNode(root,b)

但这给了我错误:

Multiple markers at this line
    - Syntax error on token ",", delete this 
     token
    - root cannot be resolved to a type
    - Return type for the method is missing

2 个答案:

答案 0 :(得分:2)

将其更改为

a.addNode(root, b);

这是因为上面的addNode(…)方法有两个参数。 希望这有帮助:)

答案 1 :(得分:-1)

public class LinkedListNode {
    public LinkedListNode next;
    int data;


    // constructor
    LinkedListNode(int newData) {
        this.data = newData;
    }

    public void addNode(LinkedListNode root, LinkedListNode node) {
        if (root.next == null) {
            root.next = node;
        }
        else {
            addNode(root.next, node);
        }
    }

    public static void main(String args[]){
        LinkedListNode root = new LinkedListNode(4);    // root
        LinkedListNode a = new LinkedListNode(16);
        LinkedListNode b = new LinkedListNode(8);
        LinkedListNode c = new LinkedListNode(23);
        LinkedListNode d = new LinkedListNode(99);
        LinkedListNode e = new LinkedListNode(1);
        LinkedListNode f = new LinkedListNode(2);
        LinkedListNode g = new LinkedListNode(5);
        LinkedListNode h = new LinkedListNode(12);

        root.addNode(root, b);
    }
}