| 论坛注册| 加入收藏 | 设为首页| RSS
Google
您当前的位置:首页 > Linux频道 > Linux开发区 > 软件开发

链表的c语言实现(四)

时间:2006-07-08 00:48:55  来源:编程中国  作者:Linux联盟收集

2、插入(后插)c6iLinux联盟
假设在一个单链表中存在2个连续结点p、q(其中p为q的直接前驱),若我们需要在p、q之间插入一个新结点s,那么我们必须先为s分配空间并赋值,然后使p的链域存储s的地址,s的链域存储q的地址即可。(p->link=s;s->link=q),这样就完成了插入操作。c6iLinux联盟
下例是应用插入算法的一个例子:c6iLinux联盟
#include <stdio.h>c6iLinux联盟
#include <malloc.h>c6iLinux联盟
#include <string.h>c6iLinux联盟
#define N 10c6iLinux联盟

typedef struct nodec6iLinux联盟
{c6iLinux联盟
char name[20];c6iLinux联盟
struct node *link;c6iLinux联盟
}stud;c6iLinux联盟

stud * creat(int n) /*建立单链表的函数*/c6iLinux联盟
{c6iLinux联盟
stud *p,*h,*s;c6iLinux联盟
int i;c6iLinux联盟
if((h=(stud *)malloc(sizeof(stud)))==NULL)c6iLinux联盟
{c6iLinux联盟
printf("不能分配内存空间!");c6iLinux联盟
exit(0);c6iLinux联盟
}c6iLinux联盟
h->name[0]='\0';c6iLinux联盟
h->link=NULL;c6iLinux联盟
p=h;c6iLinux联盟
for(i=0;i<n;i++)c6iLinux联盟
{c6iLinux联盟
if((s= (stud *) malloc(sizeof(stud)))==NULL)c6iLinux联盟
{c6iLinux联盟
printf("不能分配内存空间!");c6iLinux联盟
exit(0);c6iLinux联盟
}c6iLinux联盟
p->link=s;c6iLinux联盟
printf("请输入第%d个人的姓名:",i+1);c6iLinux联盟
scanf("%s",s->name);c6iLinux联盟
s->link=NULL;c6iLinux联盟
p=s;c6iLinux联盟
}c6iLinux联盟
return(h);c6iLinux联盟
}c6iLinux联盟

stud * search(stud *h,char *x) /*查找函数*/c6iLinux联盟
{c6iLinux联盟
stud *p;c6iLinux联盟
char *y;c6iLinux联盟
p=h->link;c6iLinux联盟
while(p!=NULL)c6iLinux联盟
{c6iLinux联盟
y=p->name;c6iLinux联盟
if(strcmp(y,x)==0)c6iLinux联盟
return(p);c6iLinux联盟
else p=p->link;c6iLinux联盟
}c6iLinux联盟
if(p==NULL)c6iLinux联盟
printf("没有查找到该数据!");c6iLinux联盟
}c6iLinux联盟

void insert(stud *p) /*插入函数,在指针p后插入*/c6iLinux联盟
{c6iLinux联盟
char stuname[20];c6iLinux联盟
stud *s; /*指针s是保存新结点地址的*/c6iLinux联盟
if((s= (stud *) malloc(sizeof(stud)))==NULL)c6iLinux联盟
{c6iLinux联盟
printf("不能分配内存空间!");c6iLinux联盟
exit(0);c6iLinux联盟
}c6iLinux联盟
printf("请输入你要插入的人的姓名:");c6iLinux联盟
scanf("%s",stuname);c6iLinux联盟
strcpy(s->name,stuname); /*把指针stuname所指向的数组元素拷贝给新结点的数据域*/c6iLinux联盟
s->link=p->link; /*把新结点的链域指向原来p结点的后继结点*/c6iLinux联盟
p->link=s; /*p结点的链域指向新结点*/c6iLinux联盟
}c6iLinux联盟

main()c6iLinux联盟
{c6iLinux联盟
int number;c6iLinux联盟
char fullname[20]; /*保存输入的要查找的人的姓名*/c6iLinux联盟
stud *head,*searchpoint;c6iLinux联盟
number=N;c6iLinux联盟
head=creat(number); /*建立新链表并返回表头指针*/c6iLinux联盟
printf("请输入你要查找的人的姓名:");c6iLinux联盟
scanf("%s",fullname);c6iLinux联盟
searchpoint=search(head,fullname); /*查找并返回查找到的结点指针*/c6iLinux联盟
insert(searchpoint); /*调用插入函数*/c6iLinux联盟
} c6iLinux联盟
c6iLinux联盟

 c6iLinux联盟

来顶一下
近回首页
返回首页
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表
相关文章
    无相关信息
栏目更新
栏目热门