在链表末尾删除

Deletion at end in linked lists

本文关键字:删除 链表      更新时间:2023-10-16

我正在尝试编写一个简单的程序,以便在链表末尾删除和插入。我已经设法在最后完美地插入了值,但我不明白删除该怎么做。

删除功能deleteend(),显示功能display(),插入功能insertend(int x)但我只对delteend()有问题。

#include<iostream>
using namespace std;
struct node
{
    int info;
    node *next;
};
node *head = NULL;
void insertend(int x)
{
    node *last = new node;
    last->info = x;
    last->next = NULL;
    if (head == NULL)
        head=last;
    else
    {
        node *temp=head;
        while(temp->next!=NULL)
            temp=temp->next;
        temp->next=last;
    }
}
void display()
{
    node *np=head;
    while(np!=NULL)
    {
        cout<<np->info<<endl;
        np=np->next;
    }
}
void deleteend()
{
    node *temp=head;
    while(temp->next!=NULL)
        temp=temp->next;
    delete temp;
}
int main()
{
    int data;
    char ch;
    do
    {
        cout<<"Enter value:";cin>>data;
        cout<<endl;
        insertend(data);
        cout<<"Enter more values?(y/n):";cin>>ch;
        cout<<endl;
    } while(ch=='y');
    cout<<"Your list is"<<endl;
    display();
    do
    {
        cout<<"Delete value from end?(y/n):";cin>>ch;
        cout<<endl;
        if(ch=='y')
            deleteend();
    } while(ch=='y');
    cout<<"Your list is"<<endl;
    display();
    return 0;
}

您需要在要删除的节点之前维护对节点的引用,以便可以正确设置指针。

由于您只支持从末尾删除,因此您的函数应该更像这样:

void deleteend()
{
    // in case we have an empty list to begin with
    if (!head) {
        return;
    }
    if (head->next == NULL) {
        // our list was one element, so delete head and set our list to null
        delete head;
        head = NULL;
        return;
    }
    // here, have a node that points to the head
    // and then have a node pointer to the next element
    // Traverse the list until you hit the end
    node *prev = head;
    node *end = head->next;
    while (end->next != NULL) {
        prev = end;
        end = end->next;
    }
    // once we're here, prev should be the second to last element
    // and end is the last element
    // so delete end and set prev->next to NULL
    delete end;
    prev->next = NULL;
}

此代码可以调整为从列表中间删除任意节点。

对于 deleteend(),您需要将下一个节点的下一个指向 null 的节点设置为什么。这可以使用两个指针来完成,一个用于当前节点,一个用于前一个节点,或者使用指向指针的指针来完成。如果使用两个指针,在具有单个节点的列表的情况下,则没有前一个节点,只有头指针。Biryee的回答显示了双指针方法。

指针指向指针的示例代码:

void deleteend()
{
node **ppnode = &head;     // ptr to head or a node's next pointer
    if(head == NULL)
        return;
    // advance ppnode so *ppnode points to last node in list
    while((*ppnode)->next != NULL)
        ppnode = &(*ppnode)->next;
    delete(*ppnode);       // delete last node
    *ppnode = NULL;        // set what was pointer to last node to NULL
}