链表的操作主要包括:
1、链表的创建
2、链表的删除
3、链表的插入
1、链表的创建
2、链表的删除
3、链表的插入
下面以单链表为例讲述这三种链表的操作:
1、链表的创建
#include <stdio.h>
struct chain
{
int value;//数据域
struct chain *next;//指针域
}
struct chain *create()
{
struct chain *head,*tail,*p;//头节点、尾节点、创建节点
int x;
head=tail=NULL;//指针初始化NULL
printf("Input data \n");
while(scanf("%d",&x)==1)
{
p=(struct chain *)malloc(sizeof(struct chain));
p->value=x;
p->next=NULL;
if(head==NULL)
{head=tail=p;}
else
{
tail=tail->next;
tail->next=p;
}
}
return head;
}
void main()
{
struct chain *p,*q;
q=creat();
while(q)
{
p=q->next;
free(q);
q=p;
}
}
2、链表的删除,本例是删除数据域为a的链表
struct chain *DelNode(head,a)
{
struct chain *p,*q;
if(head==NULL)
{printf("this is a Empty link!")}
else if(head->value==a)
{
p=head;
head=head->next;
}
else
{
p=head;
while((p->value!=a)&&(p->next!=NULL))
{
q=p;
p=p->next;
}
if(p->value==a)
{
p=p->next;
q->next=p;
free(p);
}
}
}
3、链表的插入
链表的插入分三种情况:将节点插到链表的头;将节点插到链表的中间;
将节点插到链表的尾。
#include <stdio.h>
struct chain
{
int value;//数据域
struct chain *next;//指针域
}
struct chain *insertNode(head,a,b)//head为头节点,a,b均为数据域,a
为插入地方的节点数据域,b为新插入节点的数据域
{
struct chain *p,*q,*s;
s=(struct chain *)malloc(sizeof(struct chain));
s->value=b;
if(head==NULL)//判断链表是否为空链表
{
head=s;
s->next=NULL;
}
if(head->value==a)
{
s->next=head;
head=s;//head头节点变为s,head原来的值被s链接。
}
else
{
p=head;
while((p->value!=a)&&(p->next!=NULL))
{
q=p;
p=p->next;
}//用循环进行链表的移动
if(p->value==a)
{
s->next=p;
q->next=s;
}
else //将节点插入到链表的末尾
{
p->next=s;
s->next=NULL;
}
}
return head;
}