C语言基础-单向链表静态结构与动态结构删除(跳过)结点

C语言基础-单向链表静态结构与动态结构删除(跳过)结点,第1张

非真正意义上的删除节点,而是将该链表其中一个结点断开,连接到下一个结点

 

静态链表示例题目:

为五个学生的信息建立一个静态链表,每个学生信息结构如下:

学号姓名成绩

要求输入一个学号值,删除链表中该学号学生的结点,然后输出剩下所有学生的信息。


#include
#include

struct Student
{
	long num;
	char name[20];
	float score;
	struct Student *next;
};

int main()
{
	//先创建一个单向静态链表 
	struct Student a,b,c,d,e,*head;
	a.num=10101; a.score=89.5; strcpy(a.name,"dev");
	b.num=10103; b.score=90; strcpy(b.name,"ower");
	c.num=10107; c.score=85; strcpy(c.name,"bass");
	d.num=10109; d.score=98; strcpy(d.name,"den");
	e.num=10111; e.score=97; strcpy(e.name,"ten");
	head=&a; a.next=&b; b.next=&c; c.next=&d; d.next=&e; e.next=NULL;
	
	long number; 
	int flag=1;//用于判断是否有该学生信息 
	struct Student *pt,*pb,*ph; 
	pt=ph=head;
	pb=pt->next;
	scanf("%ld",&number);
	
	do
	{
		if(number==ph->num)
		{
			flag=0;
			head=ph->next;
		}//判断首位 
		if(number==pb->num)
		{
			flag=0;
			pt->next=pb->next;
			pb=pb->next;
		}//判断接下来的位 
		else
		{
		pt=pt->next;
		pb=pt->next;
		}//如果判断当前位置与number不同,移动到下一位置继续判断 
	}while(pt->next!=NULL);//如果接下来判断的位置为空,结束循环 
	
	if(flag)printf("找不到该人");
	else 
	do
	{
		printf("\n%ld %s %f",head->num,head->name,head->score);
		head=head->next;
	}while(head!=NULL);//从首位开始输出 
	return 0;
 } 

输出结果

 

 

动态链表示例题目:

将上一题改为动态链表,并保证当输入number在信息中有多项一致均删除。


#include
#include
#define LEN sizeof(struct Student)

struct Student
{
	long num;
	char name[20];
	float score;
	struct Student *next;
}; 
int n;
//创建一个动态链表 
struct Student *creat(void)//定义一个函数,返回值为链表头地址 
{
	struct Student *head,*p1,*p2; 
	n=0;
	p1=p2=(struct Student*)malloc(LEN);//开辟一个新单元 
	scanf("%ld%s%f",&p1->num,&p1->name,&p1->score);//输入第一个学生的信息 
	head=NULL;
	while(p1->num!=0)//当输入num为0时结束循环 
	{
		n=n+1;
		if(n==1)head=p1;
		else p2->next=p1;
		p2=p1;
		p1=(struct Student*)malloc(LEN);//开辟动态存储区并赋值给p1 
		scanf("%ld%s%f",&p1->num,&p1->name,&p1->score);//输入信息 
	}
	p2->next=NULL;
	return(head);
}

int main()
{
	long number;
	int flag=1;//判断有无该人信息 
	struct Student *pt,*pb,*ph1,*ph2,*pb2;
	ph1=ph2=pt=creat();//ph1用于判断,ph2为链表头,pt指向判断数的前一个位置,用于修改next 
	pb=pb2=pt->next;//pb用于判断,pb2用于释放空间 
	printf("请输入学号:\n");
	scanf("%ld",&number);//输入判断学号 
	do
	{
		if(number==ph1->num) 
		{
			flag=0; 
			ph2=ph1->next;//将链表头指向第二个位置 
			free(ph1);//释放原链表头 
			ph1=ph2;//ph1赋值为新链表头 
		}
		if(number==pb->num)
		{
			flag=0;
			pt->next=pb->next;//连接新结点 
			pb=pb->next;//指向下一位置 
			free(pb2);//释放判断数位置内存	
			pb2=pb;//将新判断数给pb2		
		}
		else
		{
		pt=pt->next;
		pb=pt->next;
		pb2=pt->next;
		}//移位 
	}while(pb!=NULL);
	if(flag)printf("找不到该人");
	else
	{
		do
		{
			printf("\n%ld %s %f",ph2->num,ph2->name,ph2->score);
			ph2=ph2->next;
		}while(ph2!=NULL);
	 } 
	return 0;
} 

输出结果

 

 

 

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/568034.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-09
下一篇 2022-04-09

发表评论

登录后才能评论

评论列表(0条)

保存