首页 新闻 会员 周边

用链表来插入元素(C语言)

0
悬赏园豆:5 [待解决问题]

include <stdio.h>

include <stdlib.h>

struct node{//定义链表节点
int data;
struct node next;
};
int main()
{
struct node head,q,
p;//需要一个头指针,一个中间变量,一个临时变量
head=NULL;
int num,n,a,i;
printf("请输入元素个数:");
scanf("%d",&n);
for(i=0;i<n;i++){
scanf("%d",&num);
q=(struct node)malloc(sizeof(struct node));
q->data=num;
q->next=NULL;
if(head==NULL){
head=q;
}else{
p->next=q;
}
p=q;
}
struct node
t;
t=head;
printf("请输入要插入的元素:");
scanf("%d",&n);
while(t!=NULL){
if(t->next==NULL||t->next->data>n){
struct nodebase;
base=(struct node
)malloc(sizeof(struct node));
base->data=n;
base->next=t->next;//顺序问题一定不能颠倒
t->next=base;
break;
}
t=t->next;
}
t=head;
while(t!=NULL){
printf("%d ",t->data);
t=t->next;
}
return 0;
}
当我输入5 ,1 2 4 5 6,后输入3时,输出1 2 3 4 5 6;
当我输入1, 10,后输入-1时,无法输出结果,求解答

弈星的主页 弈星 | 初学一级 | 园豆:199
提问于:2020-10-15 12:39
< >
分享
所有回答(1)
0

设断点调试就可以了

会长 | 园豆:12401 (专家六级) | 2020-10-15 13:41
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册