下面实现的是一个简单的单链表
功能不多,学习使用
1#pragma once 2#include <iostream> 3using namespace std; 4 5 6 7class ListEx 8{ 9private: 10 struct Node 11 { 12 Node* next; 13 int data; 14 Node(const Node& node): data(node.data), next(nullptr) {} 15 Node(const T& d): data(d), next(nullptr) {} 16 }; 17 18private: 19 Node* head; 20 int n; //索引 21 22public: 23 ListEx(): head(nullptr), n(0) {} 24 Node* getp(int pos) 25 { 26 if (pos < 0 || pos > n) 27 { 28 return nullptr; 29 } 30 31 if (pos == 0) 32 { 33 return head; 34 } 35 36 Node* p = head; 37 38 for (int i = 1; i < pos; i++) 39 { 40 p = p->next; 41 } 42 43 return p->next; 44 } 45 46 void travel() 47 { 48 Node* p = head; 49 50 if (p == nullptr) 51 { 52 return; 53 } 54 55 p = p->next; 56 57 while (p) 58 { 59 cout << p->data << "\t" << endl; 60 p = p->next; 61 } 62 } 63 64 void insert(int d, int pos = -1) 65 { 66 if (head == nullptr) 67 { 68 head = new Node(0); 69 Node* p = new Node(d); 70 head->next = p; 71 p->next = nullptr; 72 } 73 //添加到最后 74 else if (pos < 0 || pos > n) 75 { 76 Node* p = getp(n); 77 Node* node = new Node(d); 78 p->next = node; 79 node = nullptr; 80 } 81 //添加到pos位置 82 else 83 { 84 Node* node = new Node(d); 85 86 Node* p = getp(n - 1); 87 Node* q = p->next; 88 p->next = node; 89 node->next = q; 90 } 91 92 ++n; 93 } 94 95 96 //从pos开始查找data 为d的元素,默认从0开始 97 int find(int d, int pos = 0) 98 { 99 Node* p = getp(pos); 100 101 if (p == nullptr) 102 { 103 return -1; 104 } 105 106 while (p) 107 { 108 if (p->data == d) 109 { 110 return pos; 111 } 112 113 pos++; 114 p = p->next; 115 } 116 117 return -1; 118 } 119 120 121 //从pos开始删除data为d的元素 122 bool erase(int d, int pos = 0) 123 { 124 int nIndex = find(d, pos); 125 126 if (nIndex == -1) 127 { 128 return false; 129 } 130 131 Node* p = getp(nIndex - 1); 132 Node* q = getp(nIndex); 133 134 if (p == nullptr) 135 { 136 return false; 137 } 138 139 p->next = q->next; 140 delete q; 141 return true; 142 } 143 144};
