温馨提示×

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

小亿
84
2023-12-14 10:12:33
栏目: 编程语言

以下是一个简单的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 函数中,我们创建一个空链表,然后依次插入四个节点,并最后打印整个链表。

0