求C语言大神,求编一个程序,建立链表,添加,删除,输出,查询;并对有序链表进行删除,查询,更新,急!

如题所述

#include "stdlib.h"
#include "stdio.h"
#include "conio.h"
#define NULL 0

int i;
typedef int elemtype;

typedef struct linknode
{
elemtype data;
struct linknode *next;
}nodetype;

nodetype *creat()
{
elemtype d;
nodetype *h=NULL,*s,*t;
int i=1;
printf("建立一个单链表\n");
printf("请输入各个元素的值,以空格符隔开,默认输入0结束\n");
while(1)
{
scanf("%d",&d);
if(d==0) break;
if(i==1)
{
h=(nodetype *)malloc(sizeof(nodetype));
h->data=d;h->next=NULL;t=h;
}
else
{
s=(nodetype *)malloc(sizeof(nodetype));
s->data=d;s->next=NULL;t->next=s;t=s;
}
i++;
}
return h;
}

int len(nodetype *h)
{
int i=0;
nodetype *p=h;
while(p!=NULL)
{
p=p->next;i++;
}
return i;
}

void disp(nodetype *h)
{
nodetype *p=h;
printf("输出链表如下\n");
if(p==NULL) printf("表空\n");
while(p!=NULL)
{
printf("%4d",p->data);
p=p->next;
}
printf("结束\n");
}

nodetype *findr (nodetype *h,int i)
{
nodetype *p=h;
int j=1;
if(i>len(h)||i<=0)
printf("你输入的参数不合法,找的元素不存在\n");
else
{
while(p!=NULL&&j<i)
{
j++;p=p->next;
}
}
return p;
}

nodetype *delt(nodetype *h,int i)
{
nodetype *p=h,*s;
if(i==1)
{
h=h->next;free(p);
}
else
{
p=findr(h,i-1);
if(p!=NULL&&p->next!=NULL)
{
s=p->next;
p->next=s->next;
free(s);
} else
printf("输入的值不正确\n");
}
printf("你修改后的链表值如如下输出\n");
disp(h);
return h;
}

nodetype *ins(nodetype *h,int i,elemtype x)
{
nodetype *p,*s;
s=(nodetype *)malloc(sizeof(nodetype));
s->data=x;
s->next=NULL;
if(i==0)
{
s->next=h;h=s;
}
else
{
p=findr(h,i);
if(p!=NULL)
{
s->next=p->next;
p->next=s;
}
else
printf("输入的值不合法\n");
}
printf("您插入后的链表如如下输出\n");
return h;
}

main()
{
int i=0,x=0;
nodetype *h;
h=creat();
disp(h);
printf("请输入您需要插入的元素位置i和这个接点的值x以逗号隔开:\n");
scanf("%d,%d",&i,&x);
h=ins(h,i,x);
disp(h);
printf("请输入需要删除的元素位值i\n");
scanf("%d",&i);
h=delt(h,i);
printf("请输入您需要查找的第i个接点值\n");
scanf("%d",&i);
h=findr(h,i);
if(h)
{
printf("您查找的元素存在!\n");
}
else
printf("您查找的元素不存在!\n");
system("pause");
}

这个程序实现了链表的:
建立
插入
查找
遍历输出
删除
5个功能。
温馨提示:答案为网友推荐,仅供参考