📜  C程序使用递归创建单个链接列表的副本(1)

📅  最后修改于: 2023-12-03 15:00:12.960000             🧑  作者: Mango

C程序使用递归创建单个链接列表的副本

在C程序中使用递归来创建单个链接列表的副本是一个基础的编程要求。本文将介绍使用递归来创建单个链接列表的副本的基本思路和实现方法。下面为详细代码片段及解释:

#include <stdio.h>
#include <stdlib.h>

struct node {
    int data;
    struct node *next;
};

struct node* copyList(struct node *head) {
    struct node *current_node;

    if (head == NULL) {
        return NULL;
    }

    current_node = (struct node*)malloc(sizeof(struct node));
    current_node->data = head->data;
    current_node->next = copyList(head->next); // 递归实现

    return current_node;
}

int main() {
    struct node *head = NULL;
    struct node *copy = NULL;

    // 创建链表
    head = (struct node*)malloc(sizeof(struct node));
    head->data = 1;

    head->next = (struct node*)malloc(sizeof(struct node));
    head->next->data = 2;

    head->next->next = (struct node*)malloc(sizeof(struct node));
    head->next->next->data = 3;

    // 复制链表
    copy = copyList(head);

    // 打印原链表和副本链表
    printf("Original List:\n");
    while (head != NULL) {
        printf("%d ", head->data);
        head = head->next;
    }

    printf("\nCopied List:\n");
    while (copy != NULL) {
        printf("%d ", copy->data);
        copy = copy->next;
    }

    return 0;
}
补充说明
  1. 首先定义了一个链表的节点结构体,包括一个数据域和一个指向下一个节点的指针域;
  2. 接着定义了一个函数 copyList,该函数的参数为链表的头节点 head,返回值为复制出来的新链表的头节点。函数内部首先进行异常处理,当 head 为空指针时返回空指针;否则,创建当前节点 current_node,将 head 的数据域赋值给当前节点的数据域,并递归调用 copyList 函数,将 head 的下一个节点作为参数传递进去,并将返回值(即当前节点的下一个节点)赋值给当前节点的指针域;
  3. 在主函数中创建一个原始链表,并输出原始链表和复制出来的链表的内容。

注意:

copyList 函数中,需要使用到动态内存分配,因此在复制链表使用完毕后,需要遍历链表并释放分配的内存空间,以避免出现内存泄露的问题。