单链表的基础操作by新手小白

本文介绍了一个简单的单链表实现,包括创建、插入、删除及显示等基本操作。通过C语言实现,适合初学者理解单链表的工作原理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

新手小白自己写的单链表的建立、插入、删除、输出。如果封装成不同函数应该会更加简便漂亮,我懒得改了へ(;´Д`へ)


#include <stdio.h>
#include <stdlib.h>
struct link{
int data;
struct link *next;
};
int main()
{
struct link *head;
head = (struct link*)malloc(sizeof(struct link));
head->next = NULL; 
struct link *p, *q, *a, *d;
p=head;
int i;
char c;
printf("请输入数字(以0为结尾):");
i = 0;                                                      //输入 
p = q = (struct link *)malloc(sizeof(struct link)) ;
scanf("%d",&p->data);
head = NULL;
while (p->data != 0)
{
i++;
if(i == 1)
   head = p;
else
   q->next = p;
q = p;
p = (struct link *)malloc(sizeof(struct link)) ;
scanf("%d",&p->data);
}
q->next = NULL;
printf("\n数字链表的数字为:\n");                           //输出 
a = head;
while(a != NULL)
{
printf("%6d",a->data);
a = a->next;
}
printf("\n请输入需插入的数值:");                       //插入 
int b;
scanf("%d",&b);
a = head;
while(a->next != NULL)
{
if(a->data > b)                                    //插在第一个 
{
q = (struct link *)malloc(sizeof(struct link)) ;
q->data = b;
q->next = a;
head = q;
break;
}
if(a->next->data < b)                              //插在中间 
a = a->next;
else
{
q = (struct link *)malloc(sizeof(struct link)) ;
q->data = b;
q->next = a->next;
a->next = q;
break;
}
}
if(a->next == NULL)                                   //插在最后 
{
       q = (struct link *)malloc(sizeof(struct link)) ;
       q->data = b;
a->next = q;
q->next = NULL;
}
printf("\n数字链表的数字为:\n");                           //输出 
a = head;
while(a != NULL)
{
printf("%6d",a->data);
a = a->next;
}
printf("\n请输入要删除的数值:");                          //删除 
int m;
scanf("%d",&m);
a = head;
while (a->next != NULL)
{
if(a->data == m)
{
head = a->next;
free(a);
break;
}
if(a->next->data == m)
{
   d = a->next;
   a->next = d->next;
   free(d);
   break;
}
a = a->next; 
}
if(a->next == NULL)
printf("未找到该数值"); 
printf("\n数字链表的数字为:\n");                           //输出 
a = head;
while(a != NULL)
{
printf("%6d",a->data);
a = a->next;
}
return 0;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值