在链接列表中删除最后

时间:2017-11-08 13:41:00

标签: c++ linked-list

我正在尝试编写一个简单的程序,用于在链表的末尾删除和插入。我已经成功地在最后插入了值,但我无法理解删除时要做什么。

删除功能为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;
}

2 个答案:

答案 0 :(得分: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;
}

此代码可用于从列表中间删除任意任意节点。

答案 1 :(得分:0)

对于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
}