【发布时间】:2016-01-02 19:13:55
【问题描述】:
我有这个程序,它具有创建列表的功能,如果节点的值等于函数delete_node() 的参数x,则删除节点,然后打印链接列表节点。创建和打印工作正常,但我无法删除值为x 的节点。我得到了我的原始列表或空白列表。
#include <stdio.h>
struct list {
int value;
struct list *next;
};
struct list *create_list(struct list *l, int x) {
//allocate memory for new tmp node
struct list *tmp = malloc(sizeof(struct list));
tmp->value = x;
//tmp shtohet ne koke te listes
tmp->next = l;
//l behet koka e listes
l = tmp;
return l;
}
struct list *delete_node(struct list *l, int x) {
while (l) {
if (l->value == x) {
//printf("%d", x);
struct list *tmp = malloc(sizeof(struct list));
tmp->value = l->next->value;
tmp->next = l->next->next;
l = tmp;
printf("%d ", tmp->value);
}
l = l->next;
}
return l;
}
int main() {
struct list *l = NULL;
for (int i = 5; i > -6; --i)
l = create_list(l, i);
l = delete_node(l, 3);
while (l) {
printf("%d ", l->value);
l = l->next;
}
printf("\n");
return 0;
}
【问题讨论】:
-
你正在遍历链表直到你到达末尾,因此当
x在链表的任何地方都找不到时,return l将返回 NULL。当找到x时,您将丢弃原始记录并返回下一条记录的副本,最终折腾2 条记录,然后继续遍历列表的其余部分,最终返回NULL。
标签: c++ c linked-list