#ifndef LINKLIST_H #define LINKLIST_H #include #include using namespace std; typedef int Status; #define Inf 2100000000 #define Eps 1e-6 #define ERROR 1 #define OK 0 //OVERFLOW already defined in cmath, avoid it. //#define OVERFLOW 2 template class Node{ public: Node() { next = NULL; } Node(T data) { this->data = data; next = NULL; } ~Node(){ } T data; Node* next; }; template class Linklist{ public: Linklist(); Linklist(const Linklist&); ~Linklist(); const Linklist& operator=(const Linklist& list); Status GetElem(int, T&); Status ListInsert(int, T); Status ListDelete(int, T&); Status Clear(); Status Append_head(T); Status Append(T); int GetLength(); Node* head; Node* tail; int length; }; template Linklist::Linklist() { tail = head = new Node; length = 0; } template Linklist::Linklist(const Linklist& list){ Node* p; Node* q; Node* r; p = list.head; q = head = new Node; while((p = p->next)){ r = new Node; r->data = p->data; q->next = r; q = r; } tail = q; length = list.length; } template Linklist::~Linklist() { Node* p; p = head; while(head){ p = head->next; delete head; head = p; } } template const Linklist& Linklist::operator=(const Linklist& list) { if(this != &list){ this->Clear(); Node* p; Node* q; Node* r; p = list.head; q = head; while((p = p->next)){ r = new Node; r->data = p->data; q->next = r; q = r; } tail = q; length = list.length; } return *this; } template Status Linklist::GetElem(int idx, T& data) { if(idx < 1 || idx > length) return ERROR; Node* p; p = head; for(int i = 0; i < idx; i++) p = p->next; data = p->data; return OK; } template Status Linklist::ListInsert(int idx, T data) { if(idx < 1 || idx > length + 1) return ERROR; Node* p; Node* q; q = new Node; q->data = data; p = head; for(int i = 1; i < idx; i++) p = p->next; q->next = p->next; p->next = q; if(tail->next != NULL) tail = tail->next; length++; return OK; } template Status Linklist::ListDelete(int idx, T& data) { if(idx < 1 || idx > length) return ERROR; Node* p; Node* q; p = head; for(int i = 1; i < idx; i++) p = p->next; if(p->next == tail) tail = p; data = p->next->data; q = p->next; p->next = q->next; delete q; length--; return OK; } template Status Linklist::Clear() { Node* p; Node* q; length = 0; q = head->next; while(q){ p = q->next; delete q; q = p; } tail = head; head->next = NULL; return OK; } template Status Linklist::Append_head(T data) { Node* p; p = new Node; p->data = data; p->next = head->next; head->next = p; length++; return OK; } template Status Linklist::Append(T data) { Node* p; p = new Node; p->data = data; tail->next = p; tail = p; length++; return OK; } template int Linklist::GetLength() { return length; } #endif