linklist
1. list类型简介
2. c++代码实现及stl中list的使用示例
3. 代码下载
1. list类型简单介绍
list表示线性表类型,能够动态改变长度。可以使用数组或者是链表的形式进行存储。数组形式如下:
这里使用的是链表表示,并且带有头节点。定义其上的操作如下:
1. 插入元素:insertNode
2. 删除元素:deleteNode
3. 查找元素:search
2. c++代码实现及stl中list使用示例
c++实现代码如下:
#include <iostream>
using namespace std;
struct MyListNode
{
int m_nValue;
MyListNode* next;
};
// 带头节点
class MyList
{
// 数据成员
private :
MyListNode* m_pHead;
// 操作
public :
// 打印链表
void print()
{
MyListNode* node = m_pHead->next;
while(node != NULL)
{
cout << node->m_nValue << endl;
node = node->next;
}
cout << "--------------------------" << endl;
}
// 构造函数
MyList()
{
// 产生头节点
m_pHead = new MyListNode();
// 初始化头节点内容
m_pHead->m_nValue = 0;
m_pHead->next = NULL;
}
// 析构函数,释放内存
~MyList()
{
MyListNode* node = m_pHead->next;
MyListNode* next = NULL;
while(node != NULL)
{
// 记忆该节点
next = node->next;
delete node;
node = next;
}
// 删除头节点
delete m_pHead;
}
// 插入,默认node已经初始化。O(1)
void insertNode(MyListNode* node)
{
// 如果头节点next为空
if(m_pHead->next == NULL)
{
// 第一个元素
m_pHead->next = node;
}
// 不为空
else
{
MyListNode* first = m_pHead->next;
m_pHead->next = node;
node->next = first;
}
}
// 删除,可以匹配所有情况
bool deleteNode(MyListNode* del)
{
// 第一个节点
MyListNode* prev = m_pHead;
MyListNode* next = m_pHead->next;
while(next != NULL)
{
if(next == del)
{
// 执行删除操作
prev->next = next->next;
delete next; // 释放内存
return true;
}
}
return false;
}
// 查找,第一个匹配元素
MyListNode* search(int ele)
{
MyListNode* node = m_pHead->next;
// 不空
while(node != NULL)
{
if(node->m_nValue == ele)
{
return node;
}
node = node->next;
}
return NULL;
}
};
int main()
{
MyList list;
MyListNode* node = new MyListNode();
node->m_nValue = 1;
node->next = NULL;
list.insertNode(node);
node = new MyListNode();
node->m_nValue = 2;
node->next = NULL;
list.insertNode(node);
node = new MyListNode();
node->m_nValue = 3;
node->next = NULL;
list.insertNode(node);
list.print();
// 删除
list.deleteNode(node);
list.print();
// 查找
node = list.search(1);
cout << node->m_nValue;
return 0;
}
c++中stl list使用示例如下:
#include <iostream>
#include <list>
using namespace std;
int main()
{
// 泛型声明
list<int> l;
list<int>::iterator iterator = l.begin();
// 插入元素
l.push_back(1);
l.push_back(2);
// 循环元素
for(iterator = l.begin();
iterator != l.end();
iterator++ )
{
cout << " " << *iterator;
}
// 判空
cout << endl << (l.empty() ? "该list为空" : "该list不为空");
// 清除
l.clear();
return 0;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?