2021-09-20

建立单链表,删除结点,输出链表

建立有n个结点的单链表,输出链表,然后输入一个整数x,删除所有等于x的结点,删除后再输出链表。要求有(1)创建的函数(2)删除结点的函数(3)输出链表的函数。
输入样例:
6
1 4 2 4 3 4
4
输出样例:
3 2 1


#include <stdio.h>
#include <malloc.h>
struct ming
{
	int data;
	struct ming* next;
};
struct ming* a;
struct ming* create(struct ming* a, int b[], int n);
void shanchu(struct ming* m);
void printf(struct ming* h);
int main()
{
	int b[500];
	int n, x;
	scanf("%d", &n);
	a = (struct ming*)malloc(sizeof(struct ming));
	a = create(a, b, n);

	shanchu(a);
	printf(a);
	return 0;
}
struct ming* create(struct ming* a, int b[], int n) //创建新链表并赋值
{
	struct ming* c;
	a = (struct ming*)malloc(sizeof(struct ming));
	a->next = NULL;
	for (int i = 0;i < n;i++)
	{
		c = (struct ming*)malloc(sizeof(struct ming));
		scanf("%d", &b[i]);
		c->data = b[i];
		c->next = a->next;  //此处用头插法,可以理解为逆序储存,因此输出也为逆序
		a->next = c;
	}
	return a;
}
void shanchu(struct ming* m)  //删除函数
{
	struct ming* e, * f;
	int x;
	scanf("%d", &x);
	e = a;
	f = e->next;  //用两个指针以便同步向后移,确定需要删除的结点的位置
	while (f != NULL)
	{
		if (f->data == x)
		{
			e->next = f->next;
			free(f);  //释放f这个结点
			f = e->next;  //f跳到相邻的下一个,循环继续删除
		}
		else
		{
			e = f;  //两指针同步后移
			f = e->next;
		}
	}
}
void printf(struct ming* h)  // 遍历输出
{
	struct ming* d;
	d = a->next;
	while (d != NULL)
	{
		printf("%d ", d->data);
		d = d->next;
	}
}


以下是我的运行结果
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值