2013-03-12 18 views
1

一個節點與下一節點鏈接,我會首先創建一個頭節點:如何在Java中

Node head = new Node(); 

要頭節點鏈接到下一個節點。我將分配給節點類型的節點對象中的節點

零表示節點的編號。這個節點是數字零。

Node node = new Node(0,head); 

public class Node { 

    private Object data; 
    private Node next; 

    public Node() 
    { 
    data = null; 
    next = null; 
    } 

    public Node(Object x) 
    { 
    data = x; 
    next = null; 
    } 

    public Node(Object x, Node nextNode) 
    { 
    data = x; 
    next = nextNode; 
    } 
} 

這是將節點鏈接在一起的正確方法嗎?

+0

是否行得通?它是否符合您的要求? – 2013-03-12 17:20:02

+0

與此相關的問題是,您不得不從頭開始列表(最後一個項目在開始處)。 – andre 2013-03-12 17:33:57

+0

我不明白。這怎麼可能?我以爲創建的節點是從頭到尾的,因爲我試圖將頭鏈接到第一個節點 – user983246 2013-03-12 19:59:42

回答

2

我通常看到的方式是使用LinkedList。

public class Node { 
    public Object data; 
    public Node next = null; 

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

class LinkedList{ 
    public Node head = null; 
    public Node end = null; 

    void insert(Object data) { 
     if(head == null) { 
      head = new Node(data); 
      end = head; 
     } else { 
      end.next = new Node(data); 
      end = end.next; 
     } 
    } 
} 

這是用來如下:

LinkedList= new LinkedList(); 
list.insert(2); 
list.insert(3); 
list.head; 
+0

謝謝。這絕對是查看鏈表的更好方法。 – user983246 2013-03-12 20:04:22

1

在Java中,通過引用(即指針)引用所有對象。處理實際值的唯一時間是基本類型。

這樣做next = nextNode導致next指向nextNode指向相同的位置。

TL; DR;是的。 :)

+0

我以爲從右向左分配工作。但是按照你說的方式,分配工作是從左到右的。 – user983246 2013-03-12 20:01:23