栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

链表的建立、输出、删除、插入

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

链表的建立、输出、删除、插入

 在主函数中实现多个节点的插入与删除

本代码的背景是输入学号,成绩,以0,0,终止,后输入删除节点个数,删除者学号,再然后输入添加节点个数,添加者的学号,成绩。

小编初学写的比较复杂,各位大佬还请轻点喷

代码如下:

#include
using namespace std;
#define LEN sizeof(struct student)
int n;
struct student
{
	long long int num;
	double score;
	struct student *next;
};
struct student *pt;
struct student *creat(void)//创建链表 
{
	struct student *head,*p1,*p2;
	n=0;
	p1=p2=(struct student*)malloc(LEN);//划分空间 
	//数据初始化 
	scanf("%lld%lf",&p1->num,&p1->score);
	head=NULL;
	while(p1->num!=0)
	{
		n+=1;
		if(n==1)//head 指向队头 
		{
			head=p1;
		}
		else
		{
			p2->next=p1; //将数据添加到链尾 
		}
		//重置指针 
		p2=p1;
		p1=(struct student*)malloc(LEN);
		scanf("%lld %lf",&p1->num,&p1->score);
	}
	//将链表尾部地址归零 
	p2->next=NULL;
	return (head);
}
//输出链表函数 
void print(struct student *head)
{
	struct student *p;
	p=head;//指向队头地址 
	if(head!=NULL)//队头地址不空,开始输出 
	do
	{
		printf("%lld %lfn",p->num,p->score);
		p=p->next;
	}while(p!=NULL);//当 p1 指向空地址时停止循环 
} 
//删除指定节点 
void del(long long int num,struct student *head)
{
	struct student *p,*q;
	p=head;//指向队头地址 
	if(head->num==num)
	{
		pt=head->next;
		return ;
	}
	else
	{
		while(p!=NULL)
		{
			q=p->next;
			if(q->num==num)
			{
				p->next=q->next;
				return ;
			}
			p=p->next;
		}
	}
} 
//添加指定节点
void insert(struct student *head,long long int num,double score)//插入链表末端
{
	struct student *p,*q,*qp;
	p=q=qp=(struct student*)malloc(LEN);
	p=head;
	qp->num=num;
	qp->score=score;
	
	while(p!=NULL)
	{
		q=p->next;
		if(q==NULL)
		{
			p->next=qp;
			p=p->next;
			p->next=NULL;
			return ;
		}
		p=p->next;
	}
} 
int main()
{
	pt=creat();//记录第一个节点的地址
	//链表输入 0,0 后停止,在此之后输入想要删除的节点 学号 
	int n;
	cin>>n;
	while(n--)
	{
		long long int num;
		cin>>num;
		del(num,pt);//删除节点 
	}
	cin>>n;
	while(n--)
	{
		long long int anum;
		double asorce;
		cin>>anum>>asorce;
		insert(pt,anum,asorce);
	}
	print(pt); //输出链表 
	return 0;
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/920899.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号