#include <iostream>using namespace std;typedef int T;class List{struct Node{T data;Node* next;Node(const T& d, Node* next=NULL):data(d),next(next){}};Node* head;int len;public:~List(){clear();}List():head(),len(){}int size()const{return len;}void travel()const{Node* p = head;while(p){cout << p->data << ' ';p = p->next;}cout << endl;}void clear(){Node* p = head, * q;while(p){q = p->next;delete p;p = q;}head = NULL, len = 0;}Node*& getptr(int n){if(n<0||n>len) n = len;if(n==0) return head;Node* p = head;for(int i=1; i<n; i++)p = p->next;return p->next;}void insert(const T& d, int n){Node*& p=getptr(n);Node* q = new Node(d,p);p = q;++len;}void erase(int n){Node*& p = getptr(n);if(p){Node* q = p;p = p->next;delete q;--len;}}void remove(const T& d){Node*& p = find(d);if(p){Node* q = p;p = p->next;delete q;--len;}}Node*& find(const T& d){if(len==0||head->data==d) return head;Node* p = head;while(p->next&&p->next->data!=d) p = p->next;return p->next;}void update(const T& oldv, const T& newv){Node* p = find(oldv);if(p){p->data = newv;}}T& front(){return head->data;}T& back(){return getptr(len-1)->data;}void push_front(const T& d){insert(d,0);}void push_back(const T& d){insert(d,len);}void pop_front(){erase(0);}void pop_back(){erase(len-1);}void sort(){}void reverse(){}T& operator[](int index)throw(const char*){if(index<0||index>=len) throw "越界";return getptr(index)->data;}};int main(){List l;l.insert(1,0);l.insert(2,0);l.insert(3,0);l.insert(4,4);l.insert(5,4);l.insert(6,6);l.travel();l.erase(3);l.remove(2);l.travel();l.update(5,6);l.travel();for(int i=0; i<l.size(); i++)cout << l[i] << ',';cout << endl;return 0;}
PS:供面試和筆試,或者想熟悉下LIST實現的童鞋看看