【发布时间】:2016-12-24 21:27:54
【问题描述】:
我有一个带有以下结构实现的链表:
struct _node {
int item;
struct _node *next;
}
struct _list {
struct _node *head;
struct _node *tail;
int size;
}
我想编写一个函数来克隆链表并返回一个新列表而不修改原始列表。我知道如何使用 _node 实现来做到这一点,但我不知道如何使用 _list 实现来做到这一点。
struct _node *cloneList (struct _node *head) {
if (head == NULL) return NULL;
struct _node *result = malloc(sizeof(struct _node));
result->item = head->item;
result->next = cloneList(head->next);
return result;
}
这是我所做的:
struct _list *cloneList (struct _list *list) {
if (list == NULL) return NULL;
struct _list *result = malloc(sizeof(struct _list));
result->size = list->size;
result->head = list->head;
result->tail = list->tail;
return result;
}
但这是一个错误的实现,因为它实际上并没有克隆列表,因为指向 head 和 tail 的指针仍然相同。
【问题讨论】:
-
注意你的函数不是尾递归的。
标签: c linked-list