/*List.h*/
#ifndef LIST_H
#define LIST_H
#include <iostream>
#include <memory>
using namespace std;
template<typename T> struct Node {
public:
T data;
shared_ptr<Node<T>> next;
Node() :data(0), next(nullptr) {}
Node(T x) :data(x), next(nullptr) {}
};
template<typename T> class List {
// using node = shared_ptr<Node<T>>;
public:
List();
~List();
size_t size();
bool isEmpty();
shared_ptr<Node<T>> Find(T); //查找第一个与参数相同的元素,若找到返回指向该节点的指针,找不到返回nullptr
shared_ptr<Node<T>> FindPrevious(T); //查找该元素的前驱元素,同上
shared_ptr<Node<T>> Insert(T, T); //将参数1插入到参数2之前,返回指向参数1的指针
shared_ptr<Node<T>> Append(const T); //尾后追加元素,返回新元素的指针
shared_ptr<Node<T>> Erase(T); //删除元素,返回改元素的前驱
void Print();
private:
size_t length; //链表长度
shared_ptr<Node<T>> head; //头节点
};
#endif // !LIST_H
/*List.cpp*/
#include "List.h"
using namespace std;
template<typename T>
List<T>::List() :length(0) {
head = shared_ptr<Node<T>>(new Node<T>());
}
template<typename T>
List<T>::~List() {
shared_ptr<Node<T>> current;
while (head = nullptr) {
current = head;
head = current->next;
current->next.reset();
}
}
template<typename T>
size_t List<T>::size() {
return length;
}
template<typename T>
bool List<T>::isEmpty() {
return length == 0;
}
template<typename T>
shared_ptr<Node<T>> List<T>::Find(T x) {
shared_ptr<Node<T>> current;
current = head;
while (current->data != x) {
current = current->next;
}
return current;
}
template<typename T>
shared_ptr<Node<T>> List<T>::FindPrevious(T x) {
shared_ptr<Node<T>> current;
current = head;
while (current->next->data != x) {
current = current->next;
}
return current;
}
template<typename T>
shared_ptr<Node<T>> List<T>::Insert(T x, T oldData) {
auto pre = FindPrevious(oldData);
if (pre && pre != head) {
shared_ptr<Node<T>> newNode(new Node<T>(x));
newNode->next = Find(oldData); //先让newNode和后面的链表接上,因为Find要从head开始找
pre->next = newNode;
length++;
return newNode;
}
else {
auto newNode = Append(x);
length++;
return newNode;
}
}
template<typename T>
shared_ptr<Node<T>> List<T>::Append(const T x) {
shared_ptr<Node<T>> newNode(new Node<T>(x));
shared_ptr<Node<T>> current;
current = head;
while (current->next != nullptr) {
current = current->next;
}
current->next = newNode;
length++;
return newNode;
}
template<typename T>
shared_ptr<Node<T>> List<T>::Erase(T x) {
auto it = FindPrevious(x);
if (it) {
it->next = it->next->next;
auto i = it->next;
i = nullptr;
}
else
cout << "not found" << endl;
length--;
return it;
}
template<typename T>
void List<T>::Print() {
auto it = head;
while (it != nullptr) {
cout << it->data << "->";
it = it->next;
}
}
/*test*/
#include <iostream>
#include "List.h"
#include <string>
using namespace std;
int main(int argc, char** argv) {
List<int> l;
l.Append(2);
l.Append(3);
l.Insert(1, 2);
if (!l.isEmpty())
cout << l.size() << endl;
l.Erase(2);
l.Print();
system("pause");
return 0;
}