由于最近刚写完火车票的管理系统,里面大量的用到了链表的部分,所以在这里总结一下链表的几种基本操作。
链表是什么
要用链表首先要知道链表是什么。简单的说链表就是一串存储数据的结构。说到这我们一定都会想到数组,数组也可以存储数据,但是它存储的数据在内存中是连续的,而链表存储的数据是分散的,它由每一个结点构成,并由指针将其连接起来,所以每个结点中就包含了数据域和指针域。
链表的创建
创建一个链表我们需要一个头结点,后要为头结点申请内存空间,这样就方便了链表的操作,以后在查找或者增加等等操作时,都不用再判断哪个结点是链表的第一个结点。下面是创建链表的代码。
struct node *creat()
{
struct node *phead;
phead=(struct node *)malloc(sizeof(struct node));
phead->next=NULL;
return phead;
}
链表的操作需要结构体,下面是讲解例子的结构体
struct node
{
int num;//构成链表的结点的数据(数据域)
struct node *next;//链接各个结点的指针(指针域)
};
头插法
头插法顾名思义就是从链表的头开始放,即有新的结点就把此结点放在头结点的后面,下面是头插法的代码:
void head_insert(struct node *phead)
{
struct node *p;
p=(struct node *phead)malloc(sizeof(struct node));
p->next=phead->next;
p=phead->next;
}
尾插法
尾插法顾名思义就是将新生成的结点发到最尾部,下面是代码例子:
void tail_insert(struct node *phead)
{
struct node *p,*t;
t=phead;
p=(struct node *)malloc(sizeof(struct node));
while(t->next!=NULL)
t=t->next;//找到最后一个结点
t->next=p;
p->next=NULL;
}
删除
下面是代码例子:
void delete(struct node *phead,int value)
{
struct *p,*t;
t=phead;
while(t->next!=NULL)
{
if(t->next->num==value)
{
p=t->next;
t->next=p->next;
free(p);
}
else
t=t->next;
}
以上就是链表的头插 尾插 删除的操作,下面是一整段的代码,将三者写到一个程序中
#include <stdio.h>
typedef struct node
{
int data;
struct node *next;
}Linklist;
Linklist *creat()
{
Linklist *phead;
phead=(Linklist *)malloc(sizeof(Linklist));
phead->next=NULL;
return phead;
}
void head_insert(Linklist *phead,int n)//头插法
{
Linklist *p;
int i;
for(i=0;i<n;i++)
{
p=(Linklist *)malloc(sizeof(Linklist));
scanf("%d",&p->data);
p->next=phead->next;
phead->next=p;
}
}
void tail_insert(Linklist *phead,int value)//尾插法
{
Linklist *p,*t;
int i;
t=phead;
p=(Linklist *)malloc(sizeof(Linklist));
p->data=value;
while(t->next!=NULL)
t=t->next;
t->next=p;
p->next=NULL;
}
void print(Linklist *phead)//打印链表
{
Linklist *p;
p=phead->next;
if(p==NULL)
printf("此链表为空.\n");
while(p!=NULL)
{
printf("%d ",p->data);
p=p->next;
}
printf("\n");
}
void delete(Linklist *phead,int value)//删除结点
{
Linklist *p,*t;
t=phead;
while(t->next!=NULL)
{
if(t->next->data==value)
{
p=t->next;
t->next=p->next;
free(p);
}
else
t=t->next;
}
}
int main(void)
{
Linklist *phead;
int value,num;
phead=creat();
head_insert(phead,5);
print(phead);
printf("请输入你想插入的数字:\n");
scanf("%d",&value);
tail_insert(phead,value);
print(phead);
printf("请输入你想删除的数字:\n");
scanf("%d",&num);
delete(phead,num);
print(phead);
}
链表这个东西刚开始学习的时候是好理解的,但是代码就需要多敲多练,才能熟练掌握与应用。链表的操作还有翻转和将其数据排序,将在我的 下一篇博客中写道,第一篇博客一定存在很多问题看到的朋友有自己见解的随时提出,我一定会虚心学习并且改进的☺☺☺