链表节点的删除

问题描述

建立一个链表,每个节点包括:学号、姓名、年龄。输入一个年龄,如果链表中的节点所包含的年龄等于此年龄,则删除此节点。

输入

 输入第一行为一个整数N,代表学生的个数,(N<10000);

 第二行至第N+1行为学生星系,每行为一个完整的学生信息,学号为正整数,名字为小于10个字节的字母组成,年龄为整数;

第N+2行输入年龄;

输出

删除年龄等于输入年龄的所有节点,并将剩余节点按照原序输出,每行为一个学生的信息(学号,姓名,年龄)

样例输入

15
1 孟凡盛 20
2 Mary 20
3 李慧 20
4 Rose 20
5 赵兵 20
6 John 21
7 王伟 20
8 马永刚 20
9 Mike 24
10 王五 20
11 赵大 23
12 钱二 21
13 孙三 20
14 李四 20
15 王五 20
20

样例输出

6 John 21
9 Mike 24
11 赵大 23
12 钱二 21

方法1:

#include<iostream>
using namespace std;
struct node
{
	 int n;
	 char name[50];
	 int age;
	 node * next;
};
void CreateList(node * & head,int N)
{
	node * s,* p;
	while(N--)
	{
		s=new node;
		cin>>s->n>>s->name>>s->age;
		if(head==NULL)
			head=s;
		else
			p->next=s;
		   p=s;
	}
	p->next=NULL;
	return;
}
void del(node * & head,int key)
{
	node * p;
	if(head->age==key)
	{
		p=head;
	   head=head->next;
		delete p;
		p=NULL;
		return;
	}
	for(node * q=head;q->next;q=q->next)
	{
		if(q->next->age==key)
		{
			p=q->next;
			q->next=p->next;
			delete p;
			p=NULL;
			return;
		}
	}
}
void ShowList(node * head)
{
	node * p=head;
	while(p)
	{
		cout<<p->n<<' '<<p->name<<' '<<p->age<<endl;
		p=p->next;
	}
}
int main()
{
	int a,b;
	node * head=NULL;
	cin>>a;
	CreateList(head,a);
	cin>>b;
	while(a--)
	{
	   del(head,b);
	}
    ShowList(head);
}

 方法二:


#include<iostream>
using namespace std;
struct node
{
	 int n;
	 char name[50];
	 int age;
	 node * next;
};
void CreateList(node * & head,int N)
{
	node * s,* p;
	while(N--)
	{
		s=new node;
		cin>>s->n>>s->name>>s->age;
		if(head==NULL)
			head=s;
		else
			p->next=s;
		   p=s;
	}
	p->next=NULL;
	return;
}
void Delete(node * &head,int key)
{
	node * p=head,* q;
	while(p->age==key)
	{
		head=head->next;
		delete p;
		p=head;
	}
	p=head;
	while(p->next)
	{
		if(p->next->age==key)
		{
			q=p->next;
			p->next=q->next;
			delete q;
		}
		else 
			p=p->next;
	}
}
void ShowList(node * head)
{
	node * p=head;
	while(p)
	{
		cout<<p->n<<' '<<p->name<<' '<<p->age<<endl;
		p=p->next;
	}
}
int main()
{
	int a,b;
	node * head=NULL;
	cin>>a;
	CreateList(head,a);
	cin>>b;
	Delete(head,b);
    ShowList(head);
}


​

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值