我即将实现一个能够在链表中任意插入节点的函数。下面的代码可以正常工作,在列表的第一个节点插入一个节点,但是将一个节点放在另一个节点之后则不起作用。老实说,我无法弄清楚这段代码是怎么回事。另外,当我跟踪代码时,我无法找出我的错误,请不要禁止我并帮我解决这个问题。提前谢谢。类节点来了:
public class Node {
Object Element;
Node Link;
public Node() {
this(null,null);
}
public Node(Object Element, Node Link) {
this.Element = Element;
this.Link = Link;
}
}
班级列表 :
public class List {
Node FirstNode;
Scanner UserInfo = new Scanner(System.in);
Scanner UserInput = new Scanner(System.in);
public List() {
FirstNode = null;
}
public void InsertArbitrary() {
int Location = UserInput.nextInt(); // Location of new node
if (Location == 1) {
Object Element = UserInfo.nextLine();
FirstNode = new Node(Element, FirstNode); // locates a New Node At First
} else {
Object Element = UserInfo.nextLine(); // Content of new node
Node CurrentNode ; // for searching in the list
CurrentNode = FirstNode;
for (int i = 1; i <= Location - 1; i++)
CurrentNode = CurrentNode.Link;
Node NewNode = new Node (Element , CurrentNode);
}
}
}
迭代到插入位置后,可以正确创建一个新节点并将其链接分配给下一个元素。但是,您没有做的是将上一个链接更新为 POINT 指向新节点,因此无法再从头节点访问列表的尾部。
您必须执行以下操作(未经测试):
Node FirstNode;
int Length = 0;
public List() {
FirstNode = null;
}
public void InsertArbitrary(int Location, Object Element) {
if (Location == 1 || Length == 0) {
FirstNode = new Node(Element, FirstNode); // locates a New Node At First
Length++;
} else {
Node CurrentNode ; // for searching in the list
CurrentNode = FirstNode;
for (int i = 1; i <= Location - 2 && i < Length; i++)
CurrentNode = CurrentNode.Link;
Node NewNode = new Node (Element , CurrentNode.Link);
CurrentNode.Link = NewNode;
Length++;
}
}
问题是您没有更新对下一个节点的引用。
在不给你代码的情况下(因为这是家庭作业),假设你想在伪代码中在 A 之后插入一个新的节点 X:
x.next = a.next
a.next = x
因此,链片段从a -> b
变为a -> x -> b