单链表基础操作C++实现
来源:互联网 发布:fd抓包更改数据犯法么 编辑:程序博客网 时间:2024/06/06 00:37
最近在复习数据结构,就把单链表的基础操作过了一篇
Node.h头文件:
template<class T>struct Node {T val;Node<T> *next;Node() {}Node(T nVal) {val = nVal;next = 0;}};单链表类文件:
#include <iostream>#include "Node.h"#include <stdexcept>using namespace std;template<class T>class SingleLinkList {private:int size;Node<T> *head;Node<T> *tail;Node<T> *getPointerAt(int pos) {//返回pos位置的指针 Node<T> *pNode = 0;if(pos < 0 || pos > size-1)throw out_of_range("The position is out of range!");else {pNode = head;for(int i = 1; i <= pos; i++)pNode = pNode->next; }return pNode;}public:SingleLinkList() {// 构造函数 head = tail = 0;size = 0;}// add向单链表的尾部添加节点 void add(T nval) {Node<T> *pNode = new Node<T>(nval);if(!head) {// 若链表为空 head = pNode;tail = pNode;}else {tail->next = pNode;tail = pNode;}size++;}// insertAt在指定位置插入节点void insertAt(int pos, T nval) {if(pos < 0 || pos > size)throw out_of_range("The position is out of range!");if(pos == size) {add(nval);} else if(pos == 0) {Node<T> *pNode = new Node<T>(nval);pNode->next = head;head = pNode;size++;}else {Node<T> *pNode = new Node<T>(nval);Node<T> *qNode = getPointerAt(pos-1);//找到pos位置的前一个指针 pNode->next = qNode->next;qNode->next = pNode;size++;}}// removeAt删除指定位置的节点 void removeAt(int pos) {if(size==0)throw runtime_error("the list is empty!");if(pos< 0 || pos >size-1)throw out_of_range("The position is out of range");if(size==1) {delete head;} else if(pos == 0) {Node<T> *p = head;head = head->next;delete p;} else {Node<T> *p = getPointerAt(pos-1);Node<T> *q= getPointerAt(pos);p->next = q->next;delete q;if(pos == size-1)tail = p;}size--;}// 删除链尾节点 void remove() {removeAt(size-1);}// 判断链表是否为空 bool isEmpty() {return size==0? true : false;}// 返回链表大小 int sizeV() {return size;}// 返回链首元素 T getHeadVal() {if(size == 0)throw runtime_error("The list is empty!");return head->val;}// 返回链尾元素 T getTailVal() {if(size==0)throw runtime_error("The list is empty!");return tail->val;}// 清空链表 void clear() {while(head) {Node<T> *tmp = head->next;delete head;head = tmp; }tail = 0;size = 0;}// 返回fval所在下标,-1表示没有找到 int find(T fval) {int index = 0;Node<T> *p = head;while(p) {if(p->val == fval)return index;index++;p = p->next;}return -1;}};
0 0
- 文章标题C语言实现单链表之基础操作
- C语言实现单链表基础操作--增删查改
- 单链表基础操作C++实现
- 单链表基础操作C++实现
- 单链表基础操作C++实现
- 链表基础操作+实例[C语言实现]
- 链式队列的基础操作实现(C语言)
- C常用基础操作
- 单链表的基础操作(C++实现)
- 单链表基础操作的Java实现
- 单链表的基础操作java实现
- java实现单链表的基础操作
- c语言实现单链表基础面试题
- 单链表基本操作c语实现
- 单链表操作演示----C语言实现
- C语言实现单链表的各种操作
- 单链表操作大全C语言实现
- C实现单链表的基本操作笔记
- AVI S246 格式转换 H246格式
- 互联网协议 一
- 筛选法产生素数表
- 屏蔽NSLog语句
- Ubuntu 服务配置(sysv-rc-conf)
- 单链表基础操作C++实现
- shell编程四~数学运算
- junit测试
- verilog语言RS232串口接收模块设计——串口调试工具发送数据在数码管显示
- 分享我的大型Java多用户商城系统开发的心得和困难
- java EE 应用(1)
- android 滑动动画效果
- 在Word2013中插入公式自动编号
- 网络协议 二