#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
typedef struct student
{int number;
struct student *next;
} NODE;
typedef struct student node;
typedef node *link;
link creatlist()
{
link head,p,q;
int a;
char ch;
head=(link)malloc(sizeof(struct student));
p=head;
printf("请输入相关学号:(以?结尾)/n");
while(ch!='?')
{q=(link)malloc(sizeof(struct student));
scanf("%d",&a);
q->number=a;
p->next=q;
p=q;
ch=getchar();
}
p->next=NULL;
return(head);
}
link add(link head,int a)
{int i,m; char ch; link ptr;
for(i=0;i<a;i++)
head=head->next;
printf("请输入要插入的学号(以?结尾):");
while(ch!='?')
{scanf("%d",&m);
ptr=(link)malloc(sizeof(struct student));
ptr->number=m;
ptr->next=head->next;
head->next=ptr;
head=ptr;
ch=getchar();
return 0;
}
}
void print(link head)
{head=head->next;
while(head!=NULL)
{printf("%5d",head->number);
head=head->next;
}
printf("\n") ;
}
int main()
{link a; int n;
a=creatlist();
print(a);
printf("请输入要插到第几项的项数:");
scanf("%d",n);
add(a,n);
printf("ok!");
print(a);
return 0;
}
当调用add的函数时显示停止工作,这段代码是为了建立一个链表和插入链表的实现。。求大神解答。。
ps:觉得麻烦的话不用改正,告诉我为什么会出现这种情况就行了。
在此拜谢orz
1.你的main函数里的scanf少了个&
2.然后我接着看了你的creatlist函数,你这个输入必须是输入一个数按一下回车,最后输入的数还必须加上?再按回车才行
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
typedef struct student
{
int number;
struct student *next;
} NODE;
typedef struct student node;
typedef node *link;
link creatlist()
{
link head, p, q;
int a;
char ch = ' ';
head = (link)malloc(sizeof(struct student));
p = head;
printf("请输入相关学号:(以?结尾)/n");
while (ch != '?')
{
q = (link)malloc(sizeof(struct student));
scanf("%d", &a);
q->number = a;
p->next = q;
p = q;
ch = getchar();
}
p->next = NULL;
return(head);
}
link add(link head, int a)
{
int i, m; char ch = ' '; link ptr;
for (i = 0; i<a; i++)
head = head->next;
printf("请输入要插入的学号(以?结尾):");
while (ch != '?')
{
scanf("%d", &m);
ptr = (link)malloc(sizeof(struct student));
ptr->number = m;
ptr->next = head->next;
head->next = ptr;
head = ptr;
ch = getchar();
return 0;
}
}
void print(link head)
{
head = head->next;
while (head != NULL)
{
printf("%5d", head->number);
head = head->next;
}
printf("\n");
}
int main()
{
link a; int n;
a = creatlist();
print(a);
printf("请输入要插到第几项的项数:");
scanf("%d", &n);
add(a, n);
printf("ok!");
print(a);
return 0;
}
主函数中输入n的值时没加“&”号
还有你的反斜杠是不是打错了,/n 应该是\n