Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0613· OpenAIAi2 WildChat-4.8M (AI2)

用c语言编写代码,实现用尾插法创建链表

  1. User

    用c语言编写代码,实现用尾插法创建链表

  2. Assistant

    下面是使用C语言编写的使用尾插法创建链表的代码:

    #include <stdio.h>
    #include <stdlib.h>
    
    typedef struct Node {
        int data;
        struct Node* next;
    } Node;
    
    Node* createLinkedList(int n) {
        Node* head = NULL;
        Node* tail = NULL;
    
        for (int i = 0; i < n; i++) {
            int num;
            printf("Enter value for Node %d: ", i+1);
            scanf("%d", &num);
    
            Node* newNode = (Node*)malloc(sizeof(Node));
            newNode->data = num;
            newNode->next = NULL;
    
            if (head == NULL) {
                head = newNode;
                tail = newNode;
            } else {
                tail->next = newNode;
                tail = newNode;
            }
        }
    
        return head;
    }
    
    void displayLinkedList(Node* head) {
        Node* current = head;
    
        if (current == NULL) {
            printf("Linked List is empty.\n");
            return;
        }
    
        printf("Linked List: ");
    
        while (current != NULL) {
            printf("%d ", current->data);
            current = current->next;
        }
    
        printf("\n");
    }
    
    int main() {
        int n;
        printf("Enter the number of nodes: ");
        scanf("%d", &n);
    
        Node* head = createLinkedList(n);
        displayLinkedList(head);
    
        return 0;
    }
    

    这段代码首先声明了一个结构体Node来表示链表中的每个节点。Node结构体包含一个data成员用于存储节点的值,以及一个next指针用于指向下一个节点。

    createLinkedList函数用于使用尾插法创建链表。它首先声明了头指针head和尾指针tail并初始化为NULL。然后通过循环依次读入每个节点的值,并创建一个新的节点,并将data成员设置为读入的值。然后根据链表是否为空进行不同的处理:如果链表为空,将头指针和尾指针都指向新节点;如果链表不为空,将尾指针的next指针指向新节点,并更新尾指针为新节点。最后返回头指针。

    displayLinkedList函数用于打印整个链表的值。它首先检查链表是否为空,如果为空则打印提示信息后返回。否则,从头指针开始遍历链表,逐个打印节点的值。

    main函数用于测试之前的两个函数。首先从用户输入中获取要创建的链表的节点数。然后调用createLinkedList函数创建链表并返回头指针。最后调用displayLinkedList函数打印链表的值。

    此代码实现了尾插法创建链表,并打印了最终创建的链表的值。