菜鸟请教,关于链表插入。
程序代码:
root@~ #cat ins.c
#include <stdio.h>
//定义链表
struct entry {
int val;
struct entry *next;
};
int main (void) {
int pos,num; //pos=结点,num=值
struct entry n1,n2,n3,n4,n0; //定义结构变量
struct entry *head=&n1; //定义表头
int Insert (struct entry *head,int pos,int num); //声明函数insert
//初始化各个结点
n1.val=111;
n1.next=&n2;
n2.val=222;
n2.next=&n3;
n3.val=333;
n3.next=&n4;
n4.val=444;
//定义表尾
n4.next=(struct entry *)0;
printf("Enter position and value:\n");
scanf("%i%i",&pos,&num);
//如果结点在允许范围之内则打印链表,否则退出。
if(Insert(head,pos,num)==-1) {
printf ("Insert Failue!\n");
return 1;
}else{
printf("\nAfter Insert...\n");
while(head) {
printf("%i\n",head->val);
head=head->next;
}
}
return 0;
}
//函数insert,问题就在这里,如果不写成函数,结果正确,如果写出函数, 错误就来啦。
int Insert (struct entry *head,int pos,int num) {
int i=0;
struct entry n0;
while(head&&i<pos-1) {
head=head->next;
i++;
}
if(!head||i>pos-1) return -1;
n0.val=num;
n0.next=head->next;
head->next=&n0;
}
root@~ #错误信息
程序代码:root@~ #/ins bash: /ins: No such file or directory root@~ #./ins Enter position and value: 1 999 //结点1后插入999 After Insert... 111 4202594 999 120552 Segmentation fault (core dumped) root@~ #





