c++ 如何在最后一个节点之前插入节点[已关闭]

q3qa4bjr  于 2023-03-14  发布在  其他
关注(0)|答案(1)|浏览(154)

已关闭。此问题需要details or clarity。当前不接受答案。
**想要改进此问题?**添加详细信息并通过editing this post阐明问题。

2天前关闭。
Improve this question
我有一段代码试图在最后一个节点之前插入一个节点,但是代码不起作用,为什么?

`void LinkedList::insertBefortLast(Node *newNode) {
Node* prev = nullptr;
Node* current = head;

while(current->getNext() != nullptr){

    prev = current;
    current = current->getNext();

}
prev->setNext(newNode);
newNode->setNext(current);

}`
kx1ctssn

kx1ctssn1#

你的代码看起来或多或少是正确的。可能有一个逻辑错误在那里的某个地方。而且每当我做的事情与链表我总是选择使用nullptr和使用NULL代替。它更容易掌握,但这只是我的意见。以下是一个更防错的版本,你的代码与解释。也许这些解释将解释一些事情,你可能错过了。希望这有助于。并让我知道我的代码是否有任何错误。再见

void addBeforeLast(Node *newNode)
{
    //Assumptions:
    //1. its a singly Linked list
    //2. You want to place the node before the last node.
    //3. Because of the above we need to think of what happens when:
    //a) list has 0 items
    //b) list has 1 item
    //c) list has 2 or more items

    if (head == NULL)
    {
        //if list empty
        head = newNode;
    }
    else if (head->next == NULL)
    {
        //list has 1 item
        newNode->next = head;
        head = newNode;
    }
    else
    {
        //list has 2 or more
        //we have to find the second last item
        Node *current = head;
        while(current->next->next != NULL)
        {
            current = current->next;
        }
        //now current is on second last item
        newNode->next = current->next;
        current->next = newNode;
    }
}

相关问题