【发布时间】:2016-06-11 09:10:58
【问题描述】:
假设我们有节点的双向链表
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int value;
struct Node* next;
struct Node* prev;
} Node;
typedef struct LinkedList {
Node *first;
Node *last;
} LinkedList;
void initList(LinkedList* l) {
l->first = NULL;
l->last = NULL;
}
我必须编写方法,该方法将具有给定值的新节点插入到列表的末尾并返回指向新节点的指针。我的尝试如下:
Node *insert(LinkedList *list, int value) {
Node node;
node.value = value;
node.prev = list->last;
node.next = NULL;
if (list->last != NULL){
(list->last)->next = &node;
}else{
list->first = &node;
list->last = &node;
}
return &node;
}
看起来,在空列表中的插入是有效的,但它不适用于非空列表。
(有实现测试,它告诉我插入是否成功。我可以发布它们的代码,但不认为这很重要)。
请问,错误在哪里?
日志中有警告(第51行是'return &node')
C:\...\main.c|51|warning: function returns address of local variable [-Wreturn-local-addr]|
这是严重的问题吗?以及如何去除?
谢谢大家的解答,不过我觉得非空列表还是有问题的,因为根据测试,这个失败了:
void test_insert_nonempty(){
printf("Test 2: ");
LinkedList l;
initList(&l);
Node n;
n.value = 1;
n.next = NULL;
l.first = &n;
l.last = &n;
insert(&l, 2);
if (l.last == NULL) {
printf("FAIL\n");
return;
}
if ((l.last->value == 2) && (l.last->prev != NULL)) {
printf("OK\n");
free(l.last);
}else{
printf("FAIL\n");
}
}
【问题讨论】:
标签: c dynamic data-structures linked-list doubly-linked-list