2
我正在處理鏈接列表,並且我要做一個插入函數。該列表是從包含學生姓名和分數的文件創建的,並且按照排序的方式創建,第一次嘗試我插入一個新節點即可,但第二次嘗試使新節點指向自身,而不是指向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;
}
}
我會更新問題以獲取更多錯誤細節。 –
我已經刪除了prev並插入,仍然沒有變化@ paul-ogilvie –
當你插入代碼的其他代碼時,肯定會出現錯誤,因爲他插入似乎是corect。 –