【发布时间】:2017-12-11 20:27:19
【问题描述】:
由于某种原因,如果我有一个看起来像 3->2->1->0 的链表,并且我调用了 deleteSecond(head),我会得到 3->1->0->0。这是我的代码:
#include <stdio.h>
#include <stdlib.h>
typedef struct ListNode {
int data;
struct ListNode *next;
} *LinkedList;
int deleteSecond(LinkedList list) {
if (list == NULL || list->next == NULL)
return 0;
int val = list->next->data;
LinkedList second = list->next;
list->next = list->next->next;
free(second);
return val;
}
int main() {
LinkedList head = NULL;
head = malloc(sizeof(LinkedList));
for (int i = 0; i < 4; i++) {
LinkedList newNode = malloc(sizeof(LinkedList));
newNode->data = i;
newNode->next = head;
head = newNode;
}
LinkedList ptr = head;
for (int i = 0; i < 4; i++) {
printf("%d\n", ptr->data);
ptr = ptr->next;
}
printf("\n");
deleteSecond(head);
while (head != NULL) {
printf("%d\n", head->data);
head = head->next;
}
return 0;
}
我相信我的 deleteSecond 函数应该是正确的。我创建一个指向我的第二个节点的指针,然后创建 head->next = head->next->next,然后释放指向第二个节点的指针。我不知道为什么我的列表末尾有两个 0。
【问题讨论】:
-
为什么你
typedef一个指针?这……嗯……你现在明白了……很难处理 -
head = malloc(sizeof(LinkedList));在这里你做了你不应该做的事。 -
总是使用
head = malloc(sizeof *head);,这样可以避免这个问题,也可以避免重新输入正确的类型名称……当然,只要你记得那个星号。 :) -
问题是你在循环之前分配了
head,而你从来没有为它的data或next分配任何东西。在进入填充列表的循环之前,您应该将head设置为NULL。这将解决问题 (demo)。 -
一方面,。删除一个元素后,你应该循环 3 次,而不是 4 次。更好
标签: c linked-list