我简单的理解链表就相当于在是把结构体连接起来的一个存储方式,能方便的存储更多的信息,不会想数组那样非常受内存限制。
下面一个程序是链表的几个基本操作。
#include<stdio.h>
#include<malloc.h>
int n=0;
struct lian* shanchu(struct lian *head);
struct lian* charu(struct lian *head);
struct lian* out(struct lian *head);
struct lian
{
int date;
struct lian *next;
};
int main()
{
int s;
struct lian *p1,*p2,*head=NULL;
scanf("%d",&s);
p2=p1=(struct lian *)malloc(sizeof(struct lian));
p1->date=s;
while(p1->date)
{
n++;
if(head==NULL)
head=p1;
else
p2=p1;
p1=(struct lian *)malloc(sizeof(struct lian));
p2->next=p1;
scanf("%d",&p1->date);
}
head=charu(head);
head=out(head);
return 0;
}
struct lian* shanchu(struct lian *head)
{
int a;
struct lian *p,*q;
printf("输入你想删除的值\n");
scanf("%d",&a);
for(p=head;p->next;q=p,p=p->next)
{
if(p->date==a)
{
if(p==head)
{
head=head->next;
free(p);
}
else
{
for(int i=0;i<n;i++)
{
if(p->date==a)
{
q->next=p->next;
free(p);
}
}
}
}
}
return head;
}
struct lian* charu(struct lian *head)
{
int a;
struct lian *p,*q;
printf("输入你想插入的数\n");
scanf("%d",&a);
p=head;
n++;
q=(struct lian *)malloc(sizeof(struct lian));
q->date=a;
head=q;
head->next=p;
return head;
}
struct lian* out(struct lian *head){
struct lian *p;
int i;
p=head;
for(i=0;i<n+1;i++)
{
printf("%3d",p->date);
p=p->next;
}
printf("\n");
return head;
}