#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;
}
链表操作 1
于 2022-11-13 21:35:35 首次发布
本文介绍了如何使用C语言实现链表结构,包括创建节点、插入元素到不同位置和删除指定节点。通过create函数建立链表,insert函数进行有序插入,distroy函数则用于根据名称删除节点。最后,printflist展示了完整的链表内容。
摘要由CSDN通过智能技术生成