链表
手写双链表:
#include <iostream>
// 链表节点结构体
struct ListNode {
int value;
ListNode* prev;
ListNode* next;
ListNode(int v, ListNode* p = nullptr, ListNode* n = nullptr) : value(v), prev(p), next(n) {}
};
class LinkedList {
public:
LinkedList() : head(nullptr), tail(nullptr), size(0) {}
~LinkedList() { clear(); }
// 在链表末尾添加元素
void push_back(int value) {
if (size == 0) {
head = tail = new ListNode(value);
} else {
tail->next = new ListNode(value, tail);
tail = tail->next;
}
++size;
}
// 删除链表末尾元素
void pop_back() {
if (size == 0) return;
ListNode* temp = tail;
if (size == 1) {
head = tail = nullptr;
} else {
tail = tail->prev;
tail->next = nullptr;
}
delete temp;
--size;
}
// 在指定位置插入节点
void insert(int index, int value) {
if (index < 0 || index > size) {
std::cout << "Invalid index" << std::endl;
return;
}
if (index == 0) {
head = new ListNode(value, nullptr, head);
if (size == 0) {
tail = head;
} else {
head->next->prev = head;
}
} else if (index == size) {
push_back(value);
} else {
ListNode* current = head;
for (int i = 0; i < index - 1; ++i) {
current = current->next;
}
current->next = new ListNode(value, current, current->next);
current->next->next->prev = current->next;
}
++size;
}
// 删除指定位置的节点
void erase(int index) {
if (index < 0 || index >= size) {
std::cout << "Invalid index" << std::endl;
return;
}
if (index == 0) {
ListNode* temp = head;
head = head->next;
if (head) {
head->prev = nullptr;
} else {
tail = nullptr;
}
delete temp;
} else if (index == size - 1) {
pop_back();
} else {
ListNode* current = head;
for (int i = 0; i < index; ++i) {
current = current->next;
}
current->prev->next = current->next;
current->next->prev = current->prev;
delete current;
}
--size;
}
// 清空链表
void clear() {
while (size > 0) {
pop_back();
}
}
// 获取链表长度
int get_size() const { return size; }
// 打印链表元素
void print() const {
ListNode* temp = head;
while (temp) {
std::cout << temp->value << " ";
temp = temp->next;
}
std::cout << std::endl;
}
private:
ListNode* head;
ListNode* tail;
int size;
};
int main() {
LinkedList list;
list.push_back(1);
list.push_back(2);
list.push_back(3);
list.push_back(4);
list.push_back(5);
std::cout << "List: ";
list.print();
std::cout << "Size: " << list.get_size() << std::endl;
list.pop_back();
std::cout << "List after pop_back: ";
list.print();
std::cout << "Size: " << list.get_size() << std::endl;
return 0;
}
分类:
数据结构
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)