卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章64336本站已运行4115

c语言单链表怎么写

单链表是一种线性数据结构,由节点组成,每个节点包含数据和指向下一个节点的指针。在 c 语言中,它可以用 struct 定义节点,并用指针表示链表。基本操作包括:创建链表在头部或末尾插入元素在头部、中间或末尾删除元素遍历链表

c语言单链表怎么写

C 语言单链表的实现

什么是单链表?

单链表是一种线性数据结构,它由一组连接在一起的节点组成,每个节点包含两个部分:数据域和指针域。数据域存储实际数据,而指针域指向下一个节点。

如何实现单链表?

在 C 语言中,我们可以使用 struct 定义一个节点:

struct node {
    int data;
    struct node *next;
};

然后,链表本身可以用一个指向第一个节点的指针来表示:

struct node *head;

基本操作

以下是一些基本操作的实现:

  • 创建链表:
head = NULL;  // 创建一个空链表
  • 插入元素:

在链表头部插入元素:

struct node *new_node = (struct node *)malloc(sizeof(struct node));
new_node->data = value;
new_node->next = head;
head = new_node;

在链表末尾插入元素:

struct node *new_node = (struct node *)malloc(sizeof(struct node));
new_node->data = value;
new_node->next = NULL;

if (head == NULL) {
    head = new_node;
} else {
    struct node *current = head;
    while (current->next != NULL) {
        current = current->next;
    }
    current->next = new_node;
}
  • 删除元素:

在链表头部删除元素:

if (head != NULL) {
    struct node *temp = head;
    head = head->next;
    free(temp);
}

在链表中间或末尾删除元素:

if (head != NULL) {
    struct node *current = head;
    struct node *prev = NULL;

    while (current != NULL && current->data != value) {
        prev = current;
        current = current->next;
    }

    if (current != NULL) {
        if (prev == NULL) {
            head = current->next;
        } else {
            prev->next = current->next;
        }
        free(current);
    }
}
  • 遍历链表:
struct node *current = head;

while (current != NULL) {
    // 访问当前节点的数据
    printf("%d ", current->data);
    current = current->next;
}
卓越飞翔博客
上一篇: c语言枚举怎么使用
下一篇: c语言怎么构造函数
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏