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

   2025-02-13 5480
核心提示:以下是一个简单的C语言单链表的程序代码示例:#include stdio.h#include stdlib.h// 定义链表节点结构体struct Node {int data;s

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

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言