单向链表 双向链表

下面我们先从最常见的 单向链表 开始介绍。

  1. 单向链表的实现
    在单向链表中,每个节点都包含一个数据域和指向下一个节点的指针。

单向链表的节点结构
c
复制代码
#include <stdio.h>
#include <stdlib.h>

// 定义单向链表的节点结构
struct Node {
int data; // 存储数据
struct Node* next; // 指向下一个节点的指针
};
创建新节点
c
复制代码
// 创建一个新的节点
struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node)); // 动态分配内存
if (newNode == NULL) {
printf(“内存分配失败\n”);
exit(1);
}
newNode->data = data; // 初始化数据
newNode->next = NULL; // 初始化 next 指针为 NULL
return newNode;
}
向链表头部插入节点
c
复制代码
// 向链表的头部插入一个新节点
void insertAtHead(struct Node** head, int data) {
struct Node* newNode = createNode(data); // 创建新节点
newNode->next = head; // 将新节点的 next 指向当前的头节点
head = newNode; // 更新头节点为新节点
}
向链表尾部插入节点
c
复制代码
// 向链表的尾部插入一个新节点
void insertAtTail(struct Node
head, int data) {
struct Node* newNode = createNode(data); // 创建新节点
if (head == NULL) {
// 如果链表为空,直接将新节点作为头节点
head = newNode;
return;
}
struct Node
temp = head;
while (temp->next != NULL) { // 找到链表的最后一个节点
temp = temp->next;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值