简体   繁体   English

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

[英]How to add a node to the second to last position?

So I'm trying to make a method that inserts a node at the second to last position of a linked list. 因此,我正在尝试制作一种在链表的倒数第二个位置插入节点的方法。

Ex - I want to place 2 in the second to last position of my list of [1,2,3], so my list would now be [1,2,2,3] 前-我想在[1,2,3]列表的倒数第二个位置中放置2,所以我的列表现在应该是[1,2,2,3]

I tried the following code, but it doesn't seem to work. 我尝试了以下代码,但似乎不起作用。

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. 在您要为其分配prev = node的else语句中,它应该是prev.next = node,因为prev是当前倒数第二个,因此现在该节点将取代它,因此将prev指向node并将join节点连接到链表的最后一个节点。 Try this, it should work. 试试这个,它应该起作用。

first->prev->last, now your new node should be between prev and last, so first->prev->node->last first-> prev-> last,现在您的新节点应该在prev和last之间,因此first-> prev-> node-> last

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM