我试图实现一个insertAfterNth
方法,它在双向链表上的第n个元素(从1开始,不是0)之后插入一个元素。而且,我坚持将前一个节点设置为我尝试插入的节点。在解决问题时我需要一些帮助。谢谢。在双向链表中插入元素
public class DListNode {
public DListNode next;
public DListNode prev;
public int item;
...
}
public void insertAfterNth(int n, int item) {
if (n > length() || n < 1) {
System.out.println("error: out of bounds");
return;
}
else if (n == length()) {
insertEnd(item);
}
DListNode walker = head;
int i = 1;
while (i != n) {
i++;
walker = walker.next;
}
DListNode node = new DListNode(item);
node.next = walker.next;
walker.next.prev = node; /* not sure if this line of code is right, regardless this method is giving me errors(I'm most certain that this line is causing the problem)*/
walker.next = node;
node.prev = walker;
size++;
}
看不到的问题,但你为什么不尝试和'after'节点从那里设置成'walker.next'和工作?代码会更简单。另外,将'walker'重命名为''之前'。 – fge
原则上,代码是可以的。但是您需要处理特殊情况以分别插入列表的前面或末尾。 – Henry