c语言链表问题,C语言中链表问题

写了一个程序练习链表的基本操作,包括建立链表,删除,插入,打印和查找,程序虽然可以运行,可是结果有问题,只能完成建立功能,不能完成其他几个功能,不知问题出在何处,请大家帮忙看看啊。

/*链表的基本操作*/

#include

#include

/*定义链表结点*/

typedef struct node

{ int data;

struct node *link ;

}LNode;

/*函数声明*/

LNode *createtail(int m);

LNode *locatenode(LNode *p,int x);

LNode * insertlist(LNode *head,int a,int b);

int deletelist (LNode *h,int x );

void displaylist(LNode *h);

/*主函数*/

main ()

{

LNode *L;

int number,a,b,i,e,result1,result2; /*result1,result2为控制变量*/

printf("please input the node's number:");

scanf("%d",&number);

L=createtail(number);

printf("The current list is :\n");

displaylist(L);

printf("please enter a number 'a' to be inserted before 'b': a, b=:");

scanf("%d%d",&a,&b);

result1=insertlist(L,a,b);

if(result1)

printf("Success to insert!\n");

printf("The new list is:\n");

displaylist(L);

printf("\nPlease enter the number to be deleted:\n");

scanf("%d",&e);

result2=deletelist (L,e);

if(result2)

printf("Success to delete!\nThe new list is :\n");

displaylist(L);

printf("Please press any key to quit....");

getch();

}

/*函数名:LNode *createtail(int m)

*功能:建立一个空线性链表*/

LNode *createtail(int m)

{LNode *h,*p;

int i;

h=(LNode*)malloc(sizeof(LNode));

h->link =NULL;

printf("Please input the number of the list:\n");

for(i=0;i

{

p=(LNode*)malloc(sizeof(LNode));

scanf("%d",&p->data);

p->link=h->link;

h->link=p;

}

return h;

}

/*函数名:LNode *locatenode(LNode *p,int x);

*功能:查找结点x*/

LNode *locatenode(LNode *p,int x)

{ LNode *q;

q=p;

while(q->link!=NULL&&q->data!=x)

{

q=q->link;

}

return(q);

}

/*函数名:void insertlist(LNode *head, int a,int b);

*功能:在a之前插入结点b*/

LNode *insertlist(LNode *head,int a,int b)

{

LNode *p,*q,*s; /*p指向当前结点,q指向当前结点的前驱*/

s=(LNode*)malloc(sizeof(LNode));

s->data=a;

p=q=head;

p=p->link;

if(p->data==b)

{

s->link=q->link;

q->link=s;

s->link=p;

}

else

p->link=s;

s->link=NULL;

return head;

}

/*函数名:void deletelist (LNode *h,int x );

*功能:删除结点x*/

int deletelist (LNode *h,int x )

{

LNode *p,*q; /*q为当前搜索结点的前驱,p指向当前搜索结点*/

p=q=h;

p=p->link;

if(p->data==x)

q->link=p->link;

free(p);

}

/*函数名:void displaytlist(LNode *h);

*功能:打印链表*/

void displaylist(LNode *h)

{

LNode *p;

p=h;

while(p->link!=NULL)

{p=p->link;

printf("%3d",p->data);}

printf("\n");

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值