我已经写了这段代码,按位置插入到链表中。为什么插入函数总是附加在链表的末尾?
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