链表的删除是在建好链表的功能基础上实现的
当然,删除也是分为几种情况的
1. 删除的链表为空,删除失败
2. 要删除的元素为首元素,直接把第二个结构体设为首元素即可
3. 要删除的元素为尾元素,直接把尾元素的前一个元素的Snext指针设置为空
4. 要删除的元素位于链表中间
5. 没有找打要删除的元素
#include <iostream>
#include<stdio.h>
#include<malloc.h>
using namespace std;
struct stu
{
int Inum;
double Dscore;
char Cname[30];
struct stu *Snext;
};
int main()
{
struct stu *Insert(struct stu *, struct stu *);
void List(struct stu *);
struct stu *Del(struct stu *,int);
struct stu *head, *newstu;
int Inum;
head = NULL;
printf("请输入要插入的数据以0结尾:\n");
scanf("%d",&Inum);
while(Inum)
{
newstu = (struct stu *)malloc(sizeof(struct stu));
newstu->Inum = Inum;
scanf("%lf",&newstu->Dscore);
scanf("%s",&newstu->Cname);
head = Insert(head, newstu);
scanf("%d",&Inum);
}
printf("您输入的链表为:\n");
List(head);
printf("请输入要删除的学号:\n");
scanf("%d",&Inum);
head = Del(head,Inum);
printf("您删除后的链表为:\n");
List(head);
return 0;
}
struct stu *Insert(struct stu *head,struct stu *newstu)
{
struct stu *last, *p;
p = head;
if(p == NULL)
{
head = newstu;
head->Snext = NULL;
}
else
{
while((p != NULL) && (newstu->Inum >= p->Inum))
{
last = p;
p = p->Snext;
}
if(p != NULL)
{
if(head == p)
{
head = newstu;
newstu->Snext = p;
}
else
{
newstu->Snext = last->Snext;
last->Snext = newstu;
}
}
else
{
last->Snext = newstu;
newstu->Snext = NULL;
}
}
return head;
}
void List(struct stu *head)
{
struct stu *p;
p = head;
if(p == NULL)
{
printf("此链表为空!\n");
}
else
{
while(p != NULL)
{
printf("%d\t%lf\t%s\n",p->Inum,p->Dscore,p->Cname);
p = p->Snext;
}
}
}
struct stu *Del(struct stu *head,int Inum)
{
/* 1.链表为空
2.删除头节点
3.删除尾节点
4.删除中间节点
5. 没有找打要删除的元素
*/
struct stu *p, *last;
p = head;
if(p == NULL)
{
printf("这是一个空链表!");//第一种情况
}
else
{
while(p != NULL)
{
if(p->Inum == Inum)
break;
last = p;
p = p->Snext;
}
if(p == head)
{
head = p->Snext;//第二种情况
}
else if(p->Snext == NULL)//第三种情况
{
last->Snext == NULL;
}
else if(p == NULL)//第五种情况
{
printf("未找到此学号!\n");
}
else//第四种情况
{
last->Snext = p->Snext;
}
}
return head;
}