gpt4 book ai didi

java - 如何将节点添加到倒数第二个位置?

转载 作者:行者123 更新时间:2023-12-02 01:34:20 27 4
gpt4 key购买 nike

所以我试图创建一种方法,在链表的倒数第二个位置插入一个节点。

例如 - 我想将 2 放在 [1,2,3] 列表的倒数第二个位置,所以我的列表现在是 [1,2,2,3]

我尝试了以下代码,但似乎不起作用。

public void addSecondToLast(int data){
Node node = new Node();
node.data = data;
node.next = null;

if(top == null){
node = top;
}
if(top.next == null){
node = top.next;
}
else {
Node temp = new Node();
Node prev = new Node();
temp = top;

while(temp.next != null){
prev = temp;
temp = temp.next;
}
prev = node;
node.next = temp;


}

最佳答案

In the else statement where you're assigning prev = node, it should be prev.next = node, as prev is the current second to the last, now the node will take its place, so point prev to node and join node to the last node of linked list. Try this, it should work.

first->prev->last, now your new node should be between prev and last, so first->prev->node->last

关于java - 如何将节点添加到倒数第二个位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55465386/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com