似乎无法正确添加最后一个元素。我将最后一个项目保存在临时节点中,然后创建一个新节点。然后我链接每个节点的前一个和下一个,然后将最后一个节点指向一个新的空节点。但是当我转到 print() 方法时,该空节点似乎不是列表的一部分。
看起来它应该像我的推送方法一样简单,但我似乎无法让它像它一样工作。
public class LinkedListDeque {
public DoubleNode first = new DoubleNode(null);
public DoubleNode last = new DoubleNode(null);
public DoubleNode temp;
public int N;
LinkedListDeque() {
first.next = last;
last.prev = first;
}
public static void main(String[] args) {
LinkedListDeque link = new LinkedListDeque();
link.push("banana");
link.printList();
link.enqueue("gorilla");
link.printList();
link.enqueue("spam");
}
//nested class
private class DoubleNode {
String item;
int counter = 0;
DoubleNode next;
DoubleNode prev;
DoubleNode(String i) {
this.item = i;
}
}
public void push(String item) {
System.out.println("\npush()\n******");
if (first.item == null) {
first.item = item;
first.counter++;
} else {
System.out.println("last.item = " + last.item);
DoubleNode node = new DoubleNode(item);
first.prev = node;
node.next = first;
first = node;
}
}
public void enqueue(String item) {
System.out.println("\nenqueue()\n***********");
System.out.println("adding \"" + item + "\" to the end");
if (last.item == null) {
DoubleNode node = new DoubleNode(null); //holds null node to end list
last.item = item;
last.next = node;
} else {
DoubleNode node = new DoubleNode(null);
System.out.println("node = " + node.item); //= correct item
temp = last;
last = new DoubleNode(item); //creating a new last node
System.out.println("temp = " + temp.item); //corect
//reconnect the links
temp.next.item = last.item;
}
牧羊人nacy
qq_笑_17
相关分类