单链表是一种线性数据结构,由节点组成,每个节点包含数据和指向下一个节点的指针。在 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语言单链表怎么写的详细内容,更多请关注php中文网其它相关文章!
C语言怎么学习?C语言怎么入门?C语言在哪学?C语言怎么学才快?不用担心,这里为大家提供了C语言速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号