链表问题,插入节点为什么程序无法正常退出?
创建一个包含学生学号、姓名、性别、年龄的链表,插入新节点时为什么无法正常退出?
#include <stdio.h>
#include<stdlib.h>
#include <string.h>
typedef struct _node{
char number[20];
char name[10];
char sex; /*f for female, m for male*/
int age;
struct _node *next;
}Node;
typedef struct _list{
Node* head;
}List;
void add(List* pList, Node student);
void print(List *pList);
int main(int argc, char const *argv[])
{
Node *head = NULL;
List list;
int c;
Node students;
char number[20];
list.head = NULL;
while(1){
scanf("%s", students.number);
if(students.number[0] == '0'){
break;
}
scanf(" %s %c %d",students.name, &students.sex, &students.age);
students.next = NULL;
add(&list, students);
}
print(&list);
scanf("%s\n", number);
Node students1;
Node *p;
Node *q;
int isfound = 0;
for( q = NULL, p = list.head; p ; q = p, p = p -> next){
if(p -> number == students.number){ // 若存在则删除这个结点
isfound = 1;
if(q){
q -> next = p -> next;
}else{
list.head = p ->next;
}
free(p);
break;
}
if(isfound == 0){ //这个学号不存在,则创建新的节点
strcpy(students1.number, number);
scanf("%s %c %d",students1.name, &students1.sex, &students1.age);
students.next = NULL;
add(&list, students1);
break;
}
else if(number[0] == '0'){
break;
}
}
return 0;
}
void add(List* pList, Node student)
{
//add to linked-list
Node *p = (Node*)malloc(sizeof(Node));
*p = student;
//find the last
Node *last = pList -> head;
if(last){
while(last -> next){
last = last -> next;
}
//attach
last -> next = p;
}else{
pList -> head = p;
}
}
void print(List *pList){
Node *p;
for(p = pList -> head; p; p = p -> next){
printf("%s %s %c %d\n",p -> number, p -> name, p -> sex, p -> age);
}
printf("\n");
}