【问题标题】:How to clone a linked list with a head/tail implementation?如何克隆具有头/尾实现的链表?
【发布时间】: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


【解决方案1】:

您必须将实际克隆列表元素的旧函数与仅克隆列表“管理”部分的新函数结合起来。

这样做可以稍微修改你以前的版本:

struct _node *cloneList (struct _list *list, struct _node *head) {
  if (head == NULL) return NULL;

  struct _node *result = malloc(sizeof(struct _node));
  result->item = head->item;
  if (head->next)
    result->next = cloneList(list, head->next);
  else
    list->tail = result;
  return result;
}

然后在新函数中调用它

struct _list *cloneFullList (struct _list *list) {
    if (list == NULL) return NULL;

    struct _list *result = malloc(sizeof(struct _list));
    result->size = list->size;
    if (list->head != NULL) {
      result->head = cloneList(result, list->head);
      // tail will be set in cloneList as well.
    }
    else {
      result->head = result->tail = NULL;
    }
    return result;
}

【讨论】:

    猜你喜欢
    • 2014-06-16
    • 2014-05-23
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-01
    相关资源
    最近更新 更多