2013-02-21 168 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