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