我已經寫了這段代碼,按位置插入到鏈表中。爲什麼插入函數總是附加在鏈表的末尾?
void insert(node *list, int data, int position) {
int c;
node *temp;
node *prev;
node *curr;
curr = list;
temp = malloc(sizeof(node));
temp->num = data;
if (curr == NULL) {
curr = temp;
curr->next = NULL;
} else {
while (curr != NULL && c != position) {
prev = curr;
curr = curr->next;
c++;
}
if (c = 0) {
temp->next = curr;
curr = temp;
} else if (curr == NULL) {
prev->next = temp;
} else {
prev->next = temp;
temp->next = curr;
}
}
}
但是,我相信這個塊總是執行,不管是什麼,數據都會被附加到鏈表的末尾。
else if (curr == NULL) {
prev->next = temp;
爲什麼curr
總是空?如果位置小於列表中元素的數量,它不應該爲空......
首先:'int c = 0;' – LPs