【发布时间】:2022-01-07 12:53:53
【问题描述】:
我是 java 初学者。我正在尝试编写一个在给定位置插入节点并显示整个链表的程序。但是,我的节点似乎没有被插入,当我显示链表时,只显示第一个节点值。有人可以解释我哪里出错了吗?
//这里location是索引位置。索引从 0 开始,以 size-1 结束,就像数组一样。
//插入代码
public void insertIntoCircularDoublyLinkedList(int location,int num){
Node node=new Node();
Node tempNode=head;
int index=0;
while(index<location){
tempNode=tempNode.next;
index++;
}
node.prev=tempNode.prev;
node.next=tempNode;
tempNode.prev.next=node;
tempNode.prev=node;
}
size++;
}
//遍历代码
void traverseCDLL() {
if (head != null) {
Node tempNode = head;
for (int i=0; i < size; i++) {
System.out.print(tempNode.value);
if (i != size - 1) {
System.out.print(" -> ");
}
tempNode = tempNode.next;
}
} else {
System.out.println("The CDLL does not exist.");
}
System.out.println();
}
//主要方法
public static void main(String[] args) {
CircularDoublyLinkedList CDLL=new CircularDoublyLinkedList();
CDLL.createCircularDoublyLinkedList(8);
CDLL.insertIntoCircularDoublyLinkedList(1, 1);
CDLL.insertIntoCircularDoublyLinkedList(2, 2);
CDLL.insertIntoCircularDoublyLinkedList(3, 3);
CDLL.insertIntoCircularDoublyLinkedList(4, 4);
CDLL.traverseCDLL();
}
输出:
8 -> 0 -> 0 -> 0 -> 0
【问题讨论】:
标签: java linked-list doubly-linked-list