请教C语言链表基本操作
RT自学到链表那里,书上没详细讲链表的操作,有点看不懂,希望牛人帮忙下
不要说百度,我查了很多,上面说的都不是很懂,基本都是COPY的
诚心的希望大家给点示例,要有注释的那种
相信大家都知道链表的重要性,这部分不能马虎
谢谢!!
程序代码:#include<stdio.h>
#include<malloc.h>
struct linknode
{
int data;
struct linknode *next;
};
struct linknode *create()//创建单链表
{
int d;
int i=1;
struct linknode *head,*s,*t;
head=NULL;
printf("建立一个单链表,data域数据已0结束:\n");
while(1)
{
printf("%d:",i);
scanf("%d",&d);
if(d==0)
break;
if(i==1)//建立第一个结点
{
head=(struct linknode *)malloc(sizeof(struct linknode));
head->data=d;
head->next=NULL;
t=head;
}
else//建立其余结点
{
s=(struct linknode *)malloc(sizeof(struct linknode));
s->data=d;
s->next=NULL;
t->next=s;
t=s;
}
i++;
}
return head;
}
void disp(struct linknode *head)//输出结点数据
{
struct linknode *p=head;
printf("输出一个单链表:\n");
if(p==NULL)
printf("空");
while(p!=NULL)
{
printf("%d",p->data);
p=p->next;
}
printf("\n");
}
int len(struct linknode *head)//返回单链表的长度
{
int pcount=0;//结点计数器
struct linknode *p=head;
while(p!=NULL)
{
p->next;
pcount++;
}
return pcount;
}
struct linknode *find(struct linknode *head,int i)//返回第i个结点的指针
{
struct linknode *p=head;
int j=1;
if(i>len(head)||i<0)
return NULL;
else
{
while(p!=NULL&&j<i)
{
j++;
p=p->next;
}
return p;
}
}
/*在单链表第i个结点i>0之后插入一个data域为x的结点*/
struct linknode *insert(struct linknode *head,int i,int x)
{
struct linknode *p,*s;
s=(struct linknode *)malloc(sizeof(struct linknode));
s->data=x;
s->next=NULL;
if(i==0)//插入头结点之前
{
s->next=head;
head=s;
}
else
{
p=find(head,i);//查找第i 个结点并由p指向该结点
if(p!=NULL)
{
s->next=p->next;
p->next=s;
}
else
printf("输入的i值不正确\n");
}
return head;
}
struct linknode *del(struct linknode *head,int i)//删除第i个结点
{
struct linknode *p=head,*s;
int j=i;
if(i==1)
{
head=head->next;
free(p);
}
else
{
p=find(head,i-1);//查找第i-1个结点并由p指向该结点
if(p!=NULL&&p->next!=NULL)
{
s=p->next;//s指向要删除的结点
p->next=s->next;
free(s);
}
else
printf("输入的i值不正确\n");
}
return head;
}
void dispose(struct linknode *head)
{
struct linknode *pa=head,*pb;
if(pa!=NULL)
{
pb=pa->next;
if(pb==NULL)//只有一个结点的情况
free(pa);
else
{
while(pb!=NULL)
{
free(pa);
pa=pb;
pb=pb->next;
}
free(pa);
}
}
}
这是链表的基本操作!插入!删除!和查找