温馨提示×

c语言单链表程序代码怎么写

小亿
86
2023-12-14 10:12:33
栏目: 编程语言
C语言开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

以下是一个简单的C语言单链表的程序代码示例:

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

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

// 在链表末尾插入新节点
void insertAtEnd(struct Node** head, int data) {
    // 创建新节点
    struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
    newNode->data = data;
    newNode->next = NULL;

    // 如果链表为空,则新节点为头节点
    if (*head == NULL) {
        *head = newNode;
    }
    else {
        // 找到链表末尾并插入新节点
        struct Node* current = *head;
        while (current->next != NULL) {
            current = current->next;
        }
        current->next = newNode;
    }
}

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

int main() {
    struct Node* head = NULL;

    // 依次插入节点
    insertAtEnd(&head, 1);
    insertAtEnd(&head, 2);
    insertAtEnd(&head, 3);
    insertAtEnd(&head, 4);

    // 打印链表
    printf("链表:");
    printList(head);

    return 0;
}

这个程序演示了如何创建一个单链表并插入节点。在 insertAtEnd 函数中,我们创建一个新节点并将其插入到链表的末尾。在 printList 函数中,我们遍历链表并打印节点的数据。在 main 函数中,我们创建一个空链表,然后依次插入四个节点,并最后打印整个链表。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:c语言单链表反转代码怎么写

0