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语言单链表怎么写的详细内容,更多请关注知识资源分享宝库其它相关文章!
版权声明
本站内容来源于互联网搬运,
仅限用于小范围内传播学习,请在下载后24小时内删除,
如果有侵权内容、不妥之处,请第一时间联系我们删除。敬请谅解!
E-mail:dpw1001@163.com
发表评论