插入链表问题
如题:insert函数,运行到这个函数输入的时候,输入后出现错误????
- C/C++ code
#include <stdio.h>#include <malloc.h>#include <conio.h>#define LEN sizeof(struct student)struct student{ int num; float score; struct student *next;};struct student *exproer(); //创建链表函数;void print(struct student *); //打印链表函数;struct student *del(struct student *, int num); //删除结点函数;struct student *insert(struct student *head, struct student *stu_2); //插入结点函数;void main(){ int n = 0; struct student *stu, *stu_2, *p; stu = exproer(); p = stu; print(p); printf("Please input delete NUM:"); scanf("%d", &n); print(del(p, n)); printf("Please input insert Number: "); scanf("%d", &stu_2->num); printf("Please input insert Score: "); scanf("%f", &stu_2->score); p = insert(stu, &stu_2); print(p); getch();}struct student *exproer(){ struct student *head, *p1, *p2; int n = 0; head = NULL; p1 = p2 = (struct student *)malloc(LEN); printf("Please input Number: "); scanf("%d", &p1->num); printf("Please input Score: "); scanf("%f", &p1->score); while(p1->num) { n++; if(n == 1) { head = p1; } else { p2->next = p1; } p2 = p1; p1 = (struct student *)malloc(LEN); printf("Please input Number: "); scanf("%d", &p1->num); printf("Please input Score: "); scanf("%f", &p1->score); } p2->next = NULL; return head;}void print(struct student *p){ while(p != NULL) { printf("Number = %d\t\tScore = %f\n", p->num, p->score); p = p->next; }}struct student *del(struct student *head, int num){ struct student *p1, *p2; if(head == NULL) { printf("Fuck you!!!"); goto END; } p1 = head; while(p1->num != num && p1->next != NULL) { p2 = p1; p1 = p1->next; } if(p1->num == num) { if(p1 == head) { p1 = p1->next; head = p1; } else { p2->next = p1->next; } } else { printf("Not struct Number!!"); }END: return head;}struct student *insert(struct student *head, struct student *stu_2){ struct student *p0, *p1, *p2; p1 = head; p0 = stu_2; if(head == NULL) { head = p0; p0->next = NULL; } else { while((p0->num > p1->num) && (p1->next != NULL)) { p2 = p1; p1 = p1->next; } if(p0->num <= p1->num) { if(head == p1) //p1是头结点,插入头部; { head = p0; } else //普通情况,插入中间; { p2->next = p0; } p0->next = p1; } else //p0最大,插入末尾; { p1->next = p0; p0->next = NULL; } } return head;}[解决办法]
- C/C++ code
stu_2 = (struct student*)malloc(sizeof(struct student*));//stu_2是指针,这儿要初始化分配内存。。。否则出错 p = insert(stu, stu_2);//调用insert参数有问题