求线性表例题
希望高手帮忙发个例题,刚学完C语言,现在学c语言版的数据结构,但不知道该如何写,希望牛人给发几个程序,我学习一下
程序代码:#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);
}
}
}
这是线性链表的基本操作








