数据结构中链表元素的删除

时间:2022-05-16 19:11:01
#include <iostream>
#include <string>
struct student
{
char name[20];
int age;
student* next;
};
int main()
{
using namespace std;
char deleteName[20];
cout<<"请输入要删除的结点姓名(Kaka,Deco或Terry):"<<endl;
cin>>deleteName;
student c={"Terry",30,NULL};
student b={"Deco",27,&c};
student a={"Kaka",23,&b};
student* head=&a;
student* pointer=head;
student* before=NULL;
bool isFind=false;
while(pointer)
{
if(strcmp(deleteName,(*pointer).name)==0) //寻找删除位置
{
isFind=true; //已经找到
break;
}
before=pointer; //记录删除位置前一结点的地址
pointer=(*pointer).next;
}
if(isFind)
{
if(before==NULL)
head=(*head).next; //删除链表首记录
else
{
(*before).next=(*pointer).next; //在链表中间或末尾删除
}
}
else
cout<<"未找到你输入的项"<<endl; //未找到输入数据
student* coutPointer=head; //输出链表数据
cout<<"Head->";
while(coutPointer) //while(coutPointer != NULL)
{
cout<<(*coutPointer).name<<"->"<<(*coutPointer).age<<"->";
coutPointer=(*coutPointer).next;
}
cout<<"End"<<endl;
return 0;
}