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;
}
代码中如有错误之处,欢迎各位批评指正。