#pragma once
#include <iostream>
using namespace std;
template <typename T> class Node;
template <typename T> class List;
template <typename T> class Node {
T info;
Node<T> *link;
public:
Node();
Node(const T &data);
~Node();
public:
void InsertAfter(Node<T> *P);
Node<T> *RemoveAfter();
friend class List<T>;
};
template<typename T> Node<T>::Node() {
link = NULL;
}
template<typename T> Node<T>::Node(const T &data) {
info = data;
link = NULL;
}
template<typename T> Node<T>::~Node() {
}
template<typename T> void Node<T>::InsertAfter(Node<T> *P) {
P->link = link;
link = P;
}
template<typename T> Node<T> *Node<T>::RemoveAfter() {
Node<T> *temp = NULL;
if (link) {
Node<T> *temp = link;
link = link->link;
}
return temp;
}
template<typename T> class List {
Node<T> *head, *tail;
public:
List();
~List();
public:
void MakeEmpty();
Node<T> *Find(T data);
int Length();
void PrintList();
void InsertFront(Node<T> *p);
void InsertRear(Node<T> *p);
void InsertOrder(Node<T> *ps);
Node<T> *CreatNode(T data);
Node<T> *DeleteNode(Node<T> *p);
};
template<typename T> List<T>::List() {
head = tail = new Node<T>();
}
template<typename T> List<T>::~List() {
MakeEmpty();
delete head;
}
template<typename T> void List<T>::MakeEmpty() {
Node<T> *tempP;
while (head->link) {
tempP = head->link;
head->link = tempP->link;
delete tempP;
}
tail = head;
}
template<typename T> Node<T> *List<T>::Find(T data) {
Node<T> *tempH = head->link;
while (tempH && tempH->info != data)
tempH = tempH->link;
return tempH;
}
template<typename T> int List<T>::Length() {
int cnt = 0;
Node<T> *temp = head->link;
while (temp) {
temp = temp->link;
cnt++;
}
return cnt;
}
template<typename T> void List<T>::PrintList() {
Node<T> *tempP = head->link;
while (tempP) {
cout << tempP->info << '\t';
tempP = tempP->link;
}
cout << endl;
}
template<typename T> void List<T>::InsertFront(Node<T> *p) {
p->link = head->link;
head->link = p;
if (tail == head)
tail = p;
}
template<typename T> void List<T>::InsertRear(Node<T> *p) {
p->link = tail->link;
tail->link = p;
tail = p;
}
template<typename T> void List<T>::InsertOrder(Node<T> *p) {
Node<T> *tempP = head;
while (tempP->link && p->info > tempP->link->info)
tempP = tempP->link;
tempP->InsertAfter(p);
if (tail == tempP->link)
tail = p;
}
template<typename T> Node<T> *List<T>::CreatNode(T data) {
Node<T> *tempP = new Node<T>(data);
return tempP;
}
template<typename T> Node<T> *List<T>::DeleteNode(Node<T> *p) {
Node<T>* tempP = head;
while (tempP->link && tempP->link != p)
tempP = tempP->link;
if (tail == tempP->link)
tail = tempP;
return tempP->RemoveAfter();
}