1. 删除链表中的一个节点。其主要思想就是改变链表的指针域,以此到达删除节点的目的。如下图:
我们可以通过修改节点的指针域来删除12号节点。15->next=12->next
2. 删除链表节点的算法如下:
LNode *Delete_L(LNode *L, ElemType e)
{
Lnode *q=L; *p=L;
if(L= =NULL)
{ cout<<"空链表\n";
return L;
}
if(L->data= =key)
{
q=L;
L=L->next;
delete q; //删除节点
return L;
}
while(p->data!=key && p->next!=NULL)
{
q=p;
p=p->next;
}
if(p->data= =key)
{
q->next=p->next;
delete p;//删除节点
}
else
{
cout<<"没有指定的节点";
}
return L;
}
3. 完整的程序代码如下:
#include<iostream>
#include<string>
#include<malloc.h>
using namespace std;
struct Stu
{
int age;
string name;
struct Stu* next;
};
struct Stu* CreateList() //创建链表,年龄输入0,结束输入
{
Stu *head;
head=(struct Stu*)malloc(sizeof(Stu));
Stu *p1,*p2;
if((p1=p2=(struct Stu*)malloc(sizeof(Stu)))==0)
{
cout<<"内存分配失败!"<<endl;
};
cout<<"提示:输入【0】结束输入!"<<endl;
cout<<"请输入年龄:";
cin>>p1->age;
if(p1->age==0)
{
return 0;
}
cout<<"请输入姓名:";
cin>>p1->name;
int i=0;
while(1)
{
i++;
if(i==1)
{
head=p1;
}
p2->next=p1;
p2=p1;
if((p1=(struct Stu*)malloc(sizeof(Stu)))==0)
{
cout<<"内存分配失败!"<<endl;
}
cout<<"请输入年龄:";
cin>>p1->age;
if(p1->age==0)
{
p2->next=NULL;
return head;
}
cout<<"请输入姓名:";
cin>>p1->name;
}
return head;
}
struct Stu* DeleteList(struct Stu* h, int a) //根据指定年龄,删除某个节点
{
struct Stu* p1=h;
struct Stu* p2=NULL;
if(p1==NULL)
{
cout<<"此链表为空"<<endl;
return h;
}
while(p1->next!=NULL && p1->age!=a)
{
p2=p1;
p1=p1->next;
}
if(p1->age=a)
{
if(h==p1)
{
h=p1->next;
}
else
{
p2->next=p1->next;
free(p1);
}
}
else
{
cout<<"要删除的节点不存储在!"<<endl;
}
return h;
}
void ShowList(struct Stu* h) //打印链表
{
struct Stu* hTemp=h;
while(hTemp!=NULL)
{
cout<<hTemp->age<<" "<<hTemp->name<<" "<<endl;
hTemp=hTemp->next;
}
cout<<endl;
}
int main() //主函数,调用各函数
{
int delAge;
Stu *head=(struct Stu*)malloc(sizeof(Stu));
head=CreateList();
cout<<endl<<"你输入的内容为:"<<endl;
ShowList(head);
cout<<"请输入要删除节点的值: ";
cin>>delAge;
head=DeleteList(head,delAge);
cout<<endl<<"删除指定节点后:"<<endl;
ShowList(head);
return 0;
}
注:本程序在devc++中通过测试
参考博客:C++实现单链表的创建和打印