在链表末尾删除
Deletion at end in linked lists
我正在尝试编写一个简单的程序,以便在链表末尾删除和插入。我已经设法在最后完美地插入了值,但我不明白删除该怎么做。
删除功能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
}
相关文章:
- 我们可以删除链表中静态内存中的节点吗
- C++删除链表中的元素
- 删除链表中的特定节点
- 删除链表中的节点 - 分段错误
- 使用函数引用指向节点的指针删除链表中的节点?
- 尝试删除链表的头部或中间节点时出错
- 如何删除链表中的特定节点
- 两次删除链表有什么区别?
- 当链表是列表中唯一的节点时,删除链表的头部.单联
- 删除链表节点,C++函数不起作用
- unique_ptr:删除链表条目
- 删除链表的每隔一个节点
- 如何在C++中正确删除链表的节点
- 通过此方法删除链表中的数据会发生什么情况
- 如何在C++中删除链表中的节点?
- 如何"completely"删除链表中的所有节点?
- 删除链表中的每三个节点
- 分段 删除链表的项目时出错
- 删除链表中的节点
- 删除链表中的节点函数