链表操作 1

本文介绍了如何使用C语言实现链表结构,包括创建节点、插入元素到不同位置和删除指定节点。通过create函数建立链表,insert函数进行有序插入,distroy函数则用于根据名称删除节点。最后,printflist展示了完整的链表内容。
摘要由CSDN通过智能技术生成

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct data {
	char name[50];
	int num;
	struct data* next;
};
struct data* create(struct data *head)//可以去掉直接用insert
{
	struct data* p, * pre;
	pre = head;
	char name[50];
	while (1)
	{
		scanf("%s", name, 50);
		if (strcmp(name, "#") == 0)break;

		p = (struct data*)malloc(sizeof(struct data));
		scanf("%d", &p->num);
		strcpy(p->name, name);

		if (pre == NULL)
			head = pre = p;
		else {
			pre->next = p;
			pre = p;
		}
	}
	pre->next = NULL;
	return head;
}
struct data* insert(struct data* head,char *a,int n)
{
	struct data* p, * pre;
	p=pre = head;
	while (p && p->num >= n)
	{
		pre = p;
		p = p->next;
	}
	if (p == head)//头插
	{
		pre = (struct data*)malloc(sizeof(struct data));
		strcpy(pre->name, a);
		pre->num = n;
		pre->next = head;
		head = pre;
	}
	else if(p==NULL)//尾插
	{
		p = (struct data*)malloc(sizeof(struct data));
		strcpy(p->name, a);
		p->num = n;
		p->next = NULL;
		pre->next = p;
	}
	else//中间插
	{
		struct data*mid= (struct data*)malloc(sizeof(struct data));
		strcpy(mid->name, a);
		mid->num = n;
		mid->next = p;
		pre->next = mid;
	}
	return head;
}
struct data* distroy(struct data* head,char *a)
{
	struct data* p, *pre;
	pre=p = head;
	while (strcmp(p->name, a) != 0&&p)
	{
		pre = p;
		p = p->next;
	}
	pre->next = p->next;
	free(p);
	return head;
}
void printflist(struct data* head)
{
	while (head)
	{
		printf("%s %d\n", head->name, head->num);
		head = head->next;
	}
}

int main()
{
	struct data* head = NULL;
	char a[50];
	int n;
	head=create(head);

	while (scanf("%s", a, 50), strcmp(a, "#") != 0)
	{
		scanf("%d", &n);
		head=insert(head, a, n);
	}

	while (scanf("%s", a, 50), strcmp(a, "#") != 0)
	{
		head = distroy(head, a);
	}
	printflist(head);
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值