欢迎移步博主CSDN:[CSDN博客](https://blog.csdn.net/weixin_42327790/article/details/102862704) # 数据结构----链表 ## 单链表 单链表是用一组任意的存储单元存放线性表的元素,这组存储单元可以连续也可以不连续,甚至可以零散的分布在内存中的任意位置。简单来说就是在逻辑上连续,在物理上不连续的存储单元。 代码实现:(以下代码起始位置为0) ```c++ /* * @Author: zbl * @Date: 2019-11-01 16:03:37 * @Last Modified by: zbl * @Last Modified time: 2019-11-01 17:28:40 */ #include using namespace std; //定义结点 template struct Node{ T data; Node* next = NULL; }; //单链表的定义 template class LinkList{ private: //头结点 Node* head; //链表长度 int length; public: //无参构造函数 LinkList(){} //有参构造函数 LinkList(T a[],int n); //析构函数 ~LinkList(); //定位元素x的位置 int locate(T x); //获取位置i的元素 T get(int i); //在i位置插入元素x void insert(int i , T x); //删除i位置的元素 T Delete(int i); //打印单链表 void display(); //获取单链表长度 int getLength(){return length;} }; //有参构造函数 template LinkList::LinkList(T a[],int n){ length = n; Node* tmp = new Node(); head = tmp; int i = 0; while(i* node = new Node(); node->data = a[i++]; tmp->next = node; tmp = tmp->next; } delete tmp; //下标从0开始 head = head->next; } //析构函数 template LinkList::~LinkList(){ length = 0; Node* p = head; while(p->next != NULL){ Node* tmp = p; p = p->next; tmp->next = NULL; delete tmp; } delete p; head = NULL; } //定位元素x的位置 template int LinkList::locate(T x){ if(head == NULL) throw "链表为空!"; Node* next = head; int i = 0; while(next != NULL){ if(next->data == x) return i; ++i; next = next->next; } //未找到 return -1; } //获取位置i的元素 template T LinkList::get(int i){ if(i < 0) throw "下溢"; if(i > length - 1) throw "上溢"; Node* next = head; while(i--){ next = next->next; } return next->data; } //在i位置插入元素x template void LinkList::insert(int i , T x){ if(i < 0) throw "下溢"; if(i > length) throw "上溢"; //新建结点 Node* node = new Node(); node->data = x; //头插 if(i == 0){ node->next = head; head = node; } else{ Node* tmp = head; while(--i){ tmp = tmp->next; } node->next = tmp->next; tmp->next = node; } length++; } //删除i位置的元素 template T LinkList::Delete(int i){ if(i < 0) throw "下溢"; if(i > length - 1) throw "上溢"; Node* del = head; //头删 if(i == 0){ head = head->next; } else{ Node* tmp = head; while (--i) { tmp = head->next; } del = tmp->next; tmp->next = tmp->next->next; } T x = del->data; //释放空间 delete del; length--; return x; } //打印单链表 template void LinkList::display(){ Node* tmp = head; while(tmp != NULL) { cout<data<<" "; tmp = tmp->next; } cout< linkList(a,10); linkList.display(); cout<<"头插:";linkList.insert(0,0);linkList.display();cout< 最后修改:2023 年 03 月 19 日 © 允许规范转载 打赏 赞赏作者 支付宝微信 赞 如果觉得我的文章对你有用,请随意赞赏