【发布时间】:2016-12-17 05:53:20
【问题描述】:
我已编写此代码以按位置插入到链表中。
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 总是为空?如果位置小于列表中元素的数量,它不应该为 null...
【问题讨论】:
-
首先:
int c = 0;
标签: c data-structures linked-list