关于在链表中添加两个节点的add方法的初学者java代码
我现在很难理解链表。我有一些使用节点的代码,并被要求使用迭代方法在integer参数中指定的索引位置创建一个新节点,其中存储了string参数。索引位置的旧节点应位于新插入的节点之后 以下是字段:关于在链表中添加两个节点的add方法的初学者java代码,java,linked-list,nodes,Java,Linked List,Nodes,我现在很难理解链表。我有一些使用节点的代码,并被要求使用迭代方法在integer参数中指定的索引位置创建一个新节点,其中存储了string参数。索引位置的旧节点应位于新插入的节点之后 以下是字段: // a string that contains the full name on the filesystem of an image file. private String imageName; // a reference to the next ImageNode in the li
// a string that contains the full name on the filesystem of an image file.
private String imageName;
// a reference to the next ImageNode in the linked list.
private ImageNode next;
//temporary node created to start the set of nodes
private ImageNode temp = this;
这是我到目前为止写的代码:注意getNext()返回下一个节点
private void addIter(String imageFileStr, int pos) {
int count = 0;
while(temp.getNext() != null){
temp = temp.getNext();
count++;
if(count == pos){
temp.getNext() = ???
}
}
}
这是添加两个节点的正确方法吗?如果是这样的话,这将仅在需要将节点添加到当前节点集的末尾时才起作用。我将如何修改代码,以便它允许我在集合中间添加一个节点,并使旧节点遵循上面所说的(“索引位置上的旧节点现在应该遵循新插入的节点。”)< /P>
最后,我如何创建一个变量(x),该变量等于addIter的输入,以便设置temp.getNext()=x?(目前代码中用问号表示)。您肯定需要创建一个新对象并将数据保存到其中。新对象必须指向您要添加它的下一个节点,然后temp必须指向该对象。假设您有节点A、B、C,并且希望在位置3插入一个新节点(D)。您需要在列表中迭代到节点2,即B。然后将指向B后面节点的链接保存到临时变量中,例如TempC:
node TempC=B.getNext()
。
然后,将TempC设置为要插入的节点之后的下一个节点:D.setNext(TempC)
。然后将D
设置为B
之后的下一个节点:B.setNext(D)
。结果集将是:A、B、D、C
这里我假设第一个节点是1,而不是0。在没有看到更多实现的情况下,不可能完全回答这个问题,但这里有几点:
temp.getNext()=???
没有意义,无法分配给函数调用。您需要添加一个方法setNext(ImageNode节点)
,将下一个节点设置为给定值add
方法中,您需要使用输入字符串创建一个新节点(称之为newNode
,找到当前位于pos
(称之为existingNode
)的节点),然后您需要做几件事:
- 设置
到newNode.next
之后当前的节点(或者existingNode
,如果它是列表的末尾)null
- 将
设置为existingNode.next
newNode
public void add(String item, int pos) {
if (pos > length) {
// Probably just throw an out of bounds exception
}
Node existingNode = head;
for (int i = 0; i < pos; i++)
existingNode = existingNode.getNext();
Node newNode = new Node(item);
newNode.setNext(existingNode.getNext());
existingNode.setNext(newNode);
}
public void add(字符串项,int pos){
如果(位置>长度){
//可能只是抛出一个越界异常
}
节点存在节点=头;
对于(int i=0;i
非常感谢。我觉得这很有帮助。