要创建两个单链表,可以按照以下步骤进行操作:

  1. 定义一个链表节点的结构体,包含数据和指向下一个节点的指针。

  2. 创建第一个链表的头节点,并将其指针初始化为NULL。

  3. 使用malloc函数为第一个链表的头节点分配内存空间。

  4. 输入第一个链表的数据,创建链表节点,并将节点插入到链表中。

  5. 重复步骤3和4,直到第一个链表的所有节点都被创建。

  6. 创建第二个链表的头节点,并将其指针初始化为NULL。

  7. 使用malloc函数为第二个链表的头节点分配内存空间。

  8. 输入第二个链表的数据,创建链表节点,并将节点插入到链表中。

  9. 重复步骤7和8,直到第二个链表的所有节点都被创建。

以下是一个示例代码,演示如何创建两个单链表:

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

// 定义链表节点结构体
typedef struct Node {
    int data;
    struct Node* next;
} Node;

// 创建链表节点
Node* createNode(int data) {
    Node* newNode = (Node*)malloc(sizeof(Node));
    newNode->data = data;
    newNode->next = NULL;
    return newNode;
}

// 插入节点到链表末尾
void insertNode(Node** head, int data) {
    Node* newNode = createNode(data);
    if (*head == NULL) {
        *head = newNode;
    } else {
        Node* current = *head;
        while (current->next != NULL) {
            current = current->next;
        }
        current->next = newNode;
    }
}

// 打印链表
void printList(Node* head) {
    Node* current = head;
    while (current != NULL) {
        printf('%d ', current->data);
        current = current->next;
    }
    printf('
');
}

int main() {
    Node* list1 = NULL;
    Node* list2 = NULL;

    // 创建第一个链表
    insertNode(&list1, 1);
    insertNode(&list1, 2);
    insertNode(&list1, 3);

    // 创建第二个链表
    insertNode(&list2, 4);
    insertNode(&list2, 5);
    insertNode(&list2, 6);

    // 打印链表
    printf('List 1: ');
    printList(list1);
    printf('List 2: ');
    printList(list2);

    return 0;
}

这段代码将创建两个链表,第一个链表包含1、2、3三个节点,第二个链表包含4、5、6三个节点。最后,打印出两个链表的内容。

C语言创建两个单链表的步骤及示例代码

原文地址: https://www.cveoy.top/t/topic/DQr 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录