C语言链表的基本操作(创建,遍历,删除,排序,插入)

C语言链表的基本操作

链表是编程中经常会遇到的一种存储结构,其相对于数组的存储结构而存在,链表最大的优点在于其存储是动态的,你需要多少内存空间就申请多,而不像数组那样,有时候会造成空间的浪费,有时候会导致数据的溢出。除此之外,链表相对于数组更加有利于数据的插入,删除等操作。这是由链表的结构所决定的。
链表的结构如下:在这里插入图片描述
下面这段代码展示了链表的创建,遍历,删除,排序,插入操作

#include<stdio.h>
#include<stdlib.h>
struct listnode{
	int data;
	struct listnode *next;
};
struct listnode *creat(int n){    //链表的创建
	printf("请输入要存储的数据:\n");
	struct listnode *head,*p,*q;
	int a,i;
	head=NULL;
	for(i=1;i<=n;i++){
		scanf("%d",&a);
		p=(struct listnode *)malloc(sizeof(struct listnode));
		p->data=a;
		p->next=NULL;
		if(head==NULL){
			head=p;
		}else{
			q->next=p;
		}
		q=p;
	}
	return head;
};
struct listnode *del(struct listnode*head){  //链表元素的删除
	printf("请输入要删除的数据!\n");
	int num;
	scanf("%d",&num); 
	struct listnode *p,*q;
	p=head;
	while(p!=NULL){
		if(p->data==num){
			if(p==head){
				head=p->next;
				break;
			}
			q->next=p->next;
			break;
		}
		q=p;
		p=p->next;
	}
	return head;
}
struct listnode *sort(struct listnode *head,int n){    //链表的排序
	struct listnode *p,*q;
	int i,j,t;
	for(i=0;i<n-1;i++){
		p=head;
		q=p->next;
		for(j=0;j<n-i-1;j++){
			if(p->data>q->data){
				t=p->data,p->data=q->data,q->data=t;
			}
			p=p->next;
			q=q->next;
		}
	}
	return head;
}
struct listnode *insert(struct listnode *head){  //链表元素的插入
	printf("请输入要插入的数据:\n");
	struct listnode *p,*q,*t;
	int a;
	scanf("%d",&a);
	p=head;
	while(p!=NULL){
		if(p->next==NULL||p->next->data>a){
			t=(struct listnode*)malloc(sizeof(struct listnode));
			t->data=a;
			t->next=p->next;
			p->next=t;
			break;
		}
		p=p->next;
	}
	return head; 
}
void printlist(struct listnode *head){   //链表的遍历输出
	struct listnode *t;
	t=head;
	while(t!=NULL){
		printf("%d ",t->data);
		t=t->next;
	}
}
int main()
{
	int n,c;
	struct listnode *head;
	printf("请输入要存储的数据的个数:\n");
	scanf("%d",&n);
	head=creat(n);
	printf("数据删除请按1\n"
		   "数据排序请按2\n"
		   "数据插入请按3\n");
	while(scanf("%d",&a)!=NULL){
		switch(c){
			case 1:
				head=del(head);
				printlist(head);
				break;
			case 2:
				head=sort(head,n);
				printlist(head);
				break;
			case 3:
				head=insert(head);
				printlist(head);
				break;
		}
	}
	return 0;
}

代码中如有错误之处,欢迎各位批评指正。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值