链表的问题
这是一个动态链表的程序,但是执行结果不对。不如说插入数据,在打印。打印不出全部插入的数据。大家帮看看#include "stdlib.h"
#include "malloc.h"
struct node
{
int data;
struct node *next;
};
struct node *create_list(void)
{
struct node *head;
clrscr();
head=(struct node*)malloc(sizeof(struct node));
if(head!=NULL)
{
printf("successful");
head->next=NULL;
}
else
printf("fail");
printf("\nInput any key to return menu...");
getch();
menu();
return head;
}
struct node *insert_list(struct node *head,int value)
{
struct node *n,*p,*q;
n=(struct node *)malloc(sizeof(struct node));
n->data=value;
p=head;
if(head==NULL)
{
head=n;
n->next=NULL;
}
else
{
while((p->next!=NULL)&&(p->data<value))
{q=p;p=p->next;}
if(p->data>=value)
{ if(p==head)
{
n->next=head;
head=n;
}
else
{
q->next=n;
n->next=p;
}
}
else
{
p->next=n;
n->next=NULL;
}
}
printf("\nInput any key to return menu...");
getch();
menu();
return head;
}
void print_list(struct node *head)
{
struct node *p;
clrscr();
p=head->next;
if(head==NULL)
{
printf("the list is null!!");
}
else
{
printf("print the numbers: ");
while(p!=NULL)
{
printf(" %d",p->data);
p=p->next;
}
}
printf("\nInput any key to return menu...");
getch();
menu();
}
menu()
{
int ch,num;
struct node *head;
clrscr();
printf("***********************\n");
printf("1.create\n");
printf("2.insert\n");
printf("3.print\n");
printf("4.exit\n");
printf("***********************\n");
printf("Input your choose(1-4):");
scanf("%d",&ch);
while (ch<1 || ch>4)
{ printf("Your choose is error! Input again!\n");
printf("Input your choose(1-4):");
scanf("%d",&ch);
}
switch(ch)
{
case 1: head=create_list();break;
case 2:
{
clrscr();
printf("please input the data:");
scanf("%d",&num);
head=insert_list(head,num);
break;
}
case 3: print_list(head);break;
case 4: exit(0);break;
}
getch();
}
int main(void)
{
menu();
return 0;
}