【发布时间】:2014-09-17 15:30:25
【问题描述】:
我正在尝试编写一个双向链表。以下代码通过了我的测试,但我正在为next 方向和prev 方向的新节点分配内存。具体来说,问题是我相信我不应该在push 函数中分配current,因为这些节点已经在过去的迭代中使用new 分配。但是,如果我设置 new->prev = current 而不分配 current 我会遇到分段错误。请注意,如果我不分配current 或使用->prev,下面的代码可以作为单链表正常运行。
删除 malloc for current 后,代码在打印测试后出现段错误(第一次使用 prev)。
#include <stdlib.h>
#include <stdio.h>
struct list{
int value;
struct list *next;
struct list *prev;
};
struct list *head;
struct list *tail;
void init(int val){
head = (struct list *)malloc(sizeof(struct list *));
head->value = val;
head->next = NULL;
head->prev = NULL;
tail = malloc(sizeof(struct list *));
tail->value = val;
tail->next = NULL;
tail->prev = NULL;
}
void push(int val){
struct list *new;
struct list *current;
new = (struct list *)malloc(sizeof(struct list *)); //allocate memory space for next side
current = (struct list *)malloc(sizeof(struct list *)); //allocate memory space for prev side
new->value = val;
new->next = NULL;
current = head;
while(current->next!=NULL){current = current->next;}
new->prev = current;
current->next = new;
tail = new;
}
int main(){
printf("init with 10\n");
init(10);
printf("pushing 11\n");
push(11);
printf("pushing 12\n");
push(12);
printf("pushing 13\n");
push(13);
printf("testing\n");
printf("2-1 %d\n",head->next->prev->value);
printf("3-1 %d\n",head->next->next->prev->value);
printf("h4-1 %d\n",head->next->next->next->prev->value);
printf("t-1 %d\n",tail->prev->value);
printf("t-2 %d\n",tail->prev->prev->value);
printf("t %d\n",tail->value);
}
【问题讨论】:
-
为什么
init()不初始化tail->prev = NULL;? IMO、tail和head应该在这里获得相同的值。无需致电malloc()2 次。留给其他人回答。 -
只想push一个节点,为什么还要给两个节点分配空间?
-
如果你不分配电流(你不应该这样做),那么段错误在哪里?
-
init应该声明val的类型,并且只分配头节点,并设置tail = head。push不应该为current分配节点,也不需要遍历链表找到结尾,因为tail指向结尾。
标签: c doubly-linked-list