2013-02-21 169 views
0

我正在尋找使用一種方法,它接收對象的信息,創建對象的實例,設置信息,然後創建節點並將信息設置到節點上,最後將節點插入到它所屬的鏈接列表中。鏈表只能由rfidTagString類型組織,它是一個9位十六進制表示。以下是我迄今爲止(我忽略了「由rfidTag」部分)...插入節點到鏈接列表

public class ItemList { 

    ItemInfoNode head; 
    ItemInfoNode tail; 
    ItemInfoNode cursor; 

    int listCount = 0; 

    public ItemList(){ 
     head = cursor = tail = null; 
    } 

    public void insertInfo(String name, String rfidTag, String initPosition, 
      double price) { 
     ItemInfo obj = new ItemInfo(name, rfidTag, initPosition, initPosition, price); 
     ItemInfoNode temp = new ItemInfoNode(); 
     temp.setInfo(obj); 
    } 
} 

現在我沒有絲毫線索,放什麼做的,但我會告訴你我已經試過並添加註釋,以我在哪裏丟失,並且希望完成...

ItemInfo obj = new ItemInfo(name, rfidTag, initPosition, initPosition, price); 
ItemInfoNode temp = new ItemInfoNode(); 
temp.setInfo(obj); 

if (head == null) { 
    head = temp; 
    cursor = temp; 
    tail = temp; 
    head.setNext(cursor); 
    tail.setPrev(cursor); 
    listCount++; 
} else { 
    cursor = temp; 
    cursor.setPrev(head); 
    cursor.setNext(tail); 

    System.out.println(cursor.getPrev().getInfo().getName()); 
    System.out.println(cursor.getInfo().getName()); 
    System.out.println(cursor.getNext().getInfo().getName()); 
    // Now I stop here because I do not understand how to put a 3rd in 
    // between my head and tail without losing the middle nodes info (cursor) 
    // These printlns are here to help me understand what exactly is happening! 
    // So I am rather unclear one what my next step should be 
} 

目前我正在試圖讓我的其他嘗試運行沒有出現任何例外!完成後會添加!

+0

是否有任何理由不能使用ArrayList ? – blearn 2013-02-21 04:02:18

+0

這是一個類,我不能使用任何數據結構,它必須手動進行我想你可以說,但我從來沒有像這樣使用LinkedLists,也沒有使用DLL。此外,我的文本沒有幫助我... – Sherifftwinkie 2013-02-21 04:06:46

+0

你是否希望在最後或中間插入元素?你能說出_cursor_的重要性嗎?我的意思是它代表什麼? – asifsid88 2013-02-21 04:06:48

回答

1

假設光標指向節點要插入的節點。

ItemInfo obj = new ItemInfo(name, rfidTag, initPosition, initPosition, price); 
ItemInfoNode temp = new ItemInfoNode(); 
temp.setInfo(obj); 

if(head == null){ 
    head = tail = cursor = tmp; 
} 

else{ 
    if(cursor == tail) 
    { 
    cursor.setNext(tmp); 
    tmp.setPrev(cursor); 
    tail = tmp; 
    } 
    else 
    { 
    tmp.setNext(cursor.getNext()); 
    tmp.setPrev(cursor); 

    cursor.getNext().setPrev(tmp); 
    cursor.setNext(tmp); 
    } 
} 

listCount++; 

這樣,如果首次插入節點,那麼All(head,tail和cursor)將指向第一個節點。如果有n個節點已經存在,那麼我們需要根據遊標的位置插入新節點。如果光標指向尾部,則新節點將在尾部添加,並更新尾部。如果光標指向任何其他節點(包括頭部),則在光標和尾部未觸及之後插入新節點。在這兩種情況下,頭部都未觸摸,即頭部始終指向第一個節點。 [尾將始終指向最後一個節點 - 並相應地更新]

希望這有助於!

+0

如果你有_tail_保持跟蹤,我真的找不到使用_cursor_的理由。否則,確切地告訴你正在嘗試實現什麼 – asifsid88 2013-02-21 04:21:05

+0

好吧,正如我上面所說的,我確實需要通過它們包含的ItemInfo對象的rfidTag元素來組織這些節點的順序。所以我的計劃是使用光標作爲查找節點屬於節點列表的位置的方法,然後將節點放置在節點say ... x和y之間的位置。 – Sherifftwinkie 2013-02-21 04:25:24

+0

哇這有幫助很多,非常感謝你! – Sherifftwinkie 2013-02-21 04:44:47