如何将节点添加到倒数第二个位置?
How to add a node to the second to last position?
所以我正在尝试制作一种方法,在链表的倒数第二个位置插入一个节点。
Ex - 我想将 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
所以我正在尝试制作一种方法,在链表的倒数第二个位置插入一个节点。
Ex - 我想将 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