单链表基础操作C++实现
2016-10-11 14:05
337 查看
Node.h:
template <class T> struct Node { T val; Node<T>* next; Node(T nVal) { val = nVal; next = nullptr; } Node(void){} };
#include "Node.h" #include <iostream> using namespace std; template <class T> class LinkList { int size; public: Node<T>* head; Node<T>* tail; LinkList(void) { head = tail = nullptr; size = 0; } ~LinkList(void){ Clear(); } void Add(T val) { Node<T>* pNode = new Node<T>(val); if (head == nullptr) { head = pNode; tail = pNode; } else { tail->next = pNode; tail = pNode; } size++; } bool insertAt(int pos, T val) { Node<T>* pNode = nullptr; if (pos<0 || pos>size()) { cout << "out of range" << endl; return false; } if (pos == size) { Add(val); return true; } else if (pos == 0) { pNode = new Node<T>(val); pNode->next = head; head = pNode; } else { Node<T>* pNode = GetPointerAt(pos - 1); Node<T>* newNode = new Node<T>(val); newNode->next = pNode->next; pNode->next = newNode; } size++; return true; } bool RemoveAt(int pos) { Node<T>* pNode = nullptr; if (size == 0) { cout << "list is empty" << endl; return false; } if (pos<0 || pos>size - 1) { cout << "out of range" << endl; return false; } if (size == 1) { Claer(); } else { if (pos == 0) { pNode = head; head = head->next; delete pNode; } else { Node<T>* pPreNode = GetPointerAt(pos - 1); pNode = pPreNode->next; pPreNode->next = pNode->next; delete pNode; if (pos == size - 1) tail = pPreNode; } } size--; return true; } T GetHeadVa 4000 l() { if (size == 0) { cout << "list is empty" << endl; return NULL; } return head->val; } T GetTailVal() { if (size == 0) { cout << "list is empty" << endl; return NULL; } return tail->val; } int Find(T val) { int index = 0; Node<T>* ip = head; while (ip != nullptr) { if (ip->val == val) return index; ip = ip->next; index++; } return -1; } bool IsEmpty() { return size == 0 ? true : false; } int Size(){ return size; } void Clear() { while (head != nullptr) { Node<T>* tmp = head->next; delete head; head = tmp; } tail = nullptr; size = 0; } private: Node<T>* GetPointerAt(int pos) { Node<T>* pNode = nullptr; if (pos<0 || pos>size - 1) cout << "out of range" << endl; else { pNode = head; for (int i = 1; i <= pos; i++) pNode = pNode->next; } return pNode; } };
相关文章推荐
- 单链表基础操作C++实现
- 单链表基础操作C++实现
- 单链表基础操作C++实现
- 单链表基础操作C++实现
- 单链表基础操作C++实现
- 单链表基础操作C++实现
- 单链表基础操作C++实现
- 单链表基础操作C++实现
- 单链表基础操作C++实现
- 单链表基础操作C++实现
- 单链表基础操作C++实现
- 单链表基础操作C++实现
- 单链表基础操作C++实现
- 单链表基础操作C++实现
- 单链表基础操作C++实现
- c++ 模板类实现 动态顺序表 基础操作
- 单链表基础操作的Java实现
- 在单链表的基础上用c++实现的链栈,并使用进制转换,表达式求值两个小程序来测试
- 数据结构基础(9) --单链表的设计与实现(2)之高级操作
- 单链表的基础操作java实现