【发布时间】:2016-12-19 09:17:40
【问题描述】:
我正在处理链表,我要创建一个插入函数。该列表是从包含学生姓名和分数的文件创建的,并且以排序方式创建,第一次尝试我插入一个新节点没问题,但第二次尝试使新节点指向自身而不是指向 null 或节点之前插入的位置。我似乎找不到导致节点指向自身的线在哪里,而它在第一次尝试中没有发生!
typedef struct student
{
char name[20];
int score;
struct student *next;
} Student_Data_Type;
Student_Data_Type *insert(Student_Data_Type *head, Student_Data_Type *p)
{
if(head == NULL)//if the head is empty then create list
{
head = Readfromfile(head);
}
Student_Data_Type *bufferStack = head;
Student_Data_Type *prev;
prev = malloc(sizeof(Student_Data_Type));
bool inserted = false;
while(bufferStack->next != NULL &&
strcmp(bufferStack->next->name, p->name) < 0)
{
bufferStack = bufferStack->next;
}
p->next = bufferStack->next;
bufferStack->next = p;
printf("[####] ADDED %s %d\n",bufferStack->next->name, bufferStack->next->score);//Second try says pointing to the same node
prev = bufferStack->next;
printf("[##] AND IS POINTING TO %s %d\n", prev->next->name, prev->next->score);
inserted = true;
return head;
}
这是第一个和第二个插入的输出:-
//This is the initial list created from the file
[###] DISPLAYING NAMES AND SCORE OF STUDENTS:-
[###] ChenZhiheng <-----> 67
[###] GaoSuxiang <-----> 89
[###] MaQianli <-----> 90
[###] ZhangCheng <-----> 95
1.create list(read from file)
2.display all records
3.insert a record
4.delete a record
5.query
0.exit
//INSERT ONE
[###]ENTER NAME PLZ: Noor
[###] ENTER SCORE: 88
[####] ADDED Noor 88
[##] AND IS POINTING TO ZhangCheng 95
1.create list(read from file)
2.display all records
3.insert a record
.......
//NOW DISPLAYING THE LIST AFTER INSERTING:-
[###] DISPLAYING NAMES AND SCORE OF STUDENTS:-
[###] ChenZhiheng <-----> 67
[###] GaoSuxiang <-----> 89
[###] MaQianli <-----> 90
[###] Noor <-----> 88
[###] ZhangCheng <-----> 95
1.create list(read from file)
......
//THEN THE SECOND INSERT TRY
[###]ENTER NAME PLZ: Layla
[###] ENTER SCORE: 90
[####] ADDED Layla 90
[##] AND IS POINTING TO MaQianli 90
1.create list(read from file)
......
//THEN I CALL MY DISLAY FUNCTION AGAIN AND THIS IS THE OUTPUT:
[###] DISPLAYING NAMES AND SCORE OF STUDENTS:-
[###] ChenZhiheng <-----> 67
[###] GaoSuxiang <-----> 89
[###] Layla <-----> 90
[###] MaQianli <-----> 90
[###] Layla <-----> 90
[###] MaQianli <-----> 90
[###] Layla <-----> 90
[###] MaQianli <-----> 90
[###] Layla <-----> 90
[###] MaQianli <-----> 90
....AND FOREVER LOOP,...
//HERE IS MY DISPLAY FUNCTION
void DisplayAll(Student_Data_Type *head)
{
Student_Data_Type *stackbuffer = head;
printf("[###] DISPLAYING NAMES AND SCORE OF STUDENTS:- \n");
while(stackbuffer != NULL)
{
printf("[###] %s <-----> %d\n", stackbuffer->name, stackbuffer->score);
stackbuffer = stackbuffer->next;
}
}
【问题讨论】:
标签: c data-structures struct linked-list insert