简体   繁体   中英

Delete last node from single-linked list

I have to write a method that's going to delete the last node from the List. Do you guys have any ideas on how I should approach this?

If you have a single-linked list, you have no choice but to iterate through the entire list to the last node, maintaining a pointer to the previous node so you can reset its next field when freeing the last node:

if (head)
{
    node *curNode = head;
    node *prevNode = NULL;

    while (curNode->next)
    {
        prevNode = curNode;
        curNode = curNode->next;
    }

    if (prevNode) prevNode->next = NULL;
    delete curNode;
}

If you were using a double-linked list instead, this would be easier, as you can keep a pointer to the last node in the list and just operate on it directly:

if (head == tail)
{
    delete head;
    head = tail = NULL;
}
else if (tail)
{
    node *curNode = tail;
    tail = curNode->previous; 
    tail->next = NULL;
    delete curNode;
}

Of course, if you are really using C++ then you should be using the STL's std::list (double-linked) or std::forward_list (single-linked) containers instead, which handle these details for you.

To delete the last element on a list all you need to do is maintain two separate nodes. Initially one should point to the head of the list and the other should point to the second element on the list. You should do something like the following :

if(head == NULL)
     return 0;
else if(head->next == NULL){
     Node *temp = head;
     delete temp;
     head = NULL;
}
else{
    Node *one = head;
    Node *two = head->next;
    while(two->next != NULL){
         two = two->next;
         one = one->next;
    }
    one->next = NULL;
    delete two;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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