当前位置:首页C语言 > 正文

C语言线性表之线性链表(单链表)

作者:野牛程序员:2023-08-23 11:46:13C语言阅读 2595

线性链表,通常称为单链表(Singly Linked List),是一种基本的数据结构,由一系列的节点组成,每个节点包含数据和指向下一个节点的指针。单链表的操作涉及节点的创建、插入、删除等。以下是一个简单的单链表的示例代码:

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

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

// 创建单链表
Node* createLinkedList(int n) {
    if (n <= 0) {
        return NULL;
    }
    
    Node *head = NULL;
    Node *prev = NULL;
    
    for (int i = 1; i <= n; i++) {
        Node *newNode = (Node *)malloc(sizeof(Node));
        newNode->data = i;
        newNode->next = NULL;
        
        if (prev == NULL) {
            head = newNode;
        } else {
            prev->next = newNode;
        }
        
        prev = newNode;
    }
    
    return head;
}

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

// 销毁单链表
void destroyLinkedList(Node *head) {
    Node *current = head;
    while (current != NULL) {
        Node *temp = current->next;
        free(current);
        current = temp;
    }
}

int main() {
    int n;
    printf("请输入单链表的大小:");
    scanf("%d", &n);
    
    Node *head = createLinkedList(n);
    
    printf("单链表内容:");
    printLinkedList(head);
    
    destroyLinkedList(head);
    
    return 0;
}

在这段代码中,Node 结构表示单链表的节点,每个节点包含数据和一个指向下一个节点的指针。createLinkedList 函数用于创建单链表,printLinkedList 函数用于打印单链表的内容,destroyLinkedList 函数用于销毁单链表。单链表的操作相对简单,但需要注意正确处理指针的关系,以避免内存泄漏或指针错误。需要注意,单链表的插入和删除操作可能需要更复杂的逻辑,涉及指针的重新指向。


野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892
野牛程序员教少儿编程与信息学竞赛-微信|电话:15892516892
相关推荐

最新推荐

热门点击