单链表实现
来源:互联网 发布:网络歌手夕阳醉了 编辑:程序博客网 时间:2024/06/06 02:05
template <class Elem> class Link {public: Elem element; Link *next; Link(const Elem& elemval, Link* nextval = NULL) { element = elemval; next = nextval; } Link(Link* nextval = NULL) { next = nextval; }};template <class Elem> class LList: public List<Elem> {private: Link<Elem>* head; Link<Elem>* tail; Link<Elem>* fence; int leftcnt; int rightcnt; void init() { fence = tail = head = new Link<Elem>; leftcnt = rightcnt = 0; } void removeall() { while (head != NULL) { fence = head; head = head->next; delete fence; } }public: LList(int size=DefaultListSize) { init(); } ~LList() { removeAll(); } void clear() { removeAll(); init(); } bool insert(const Elem&); bool append(const Elem&); bool remove(Elem&); void setStart() { fence = head; rightcnt += leftcnt; leftcnt = 0; } void setEnd() { fence = tail; leftcnt += rightcnt; rightcnt = 0; } void prev(); void next() { if (fence != tail) { fence = fence->next; rightcnt--; leftcnt++; } } int leftLength() const { return leftcnt; } int rightLength() const { return rightcnt; // rightcnt是fence右边的元素个数} bool setPos(int pos); bool getValue(Elem& it) const { if (rightLength() == 0) return false; it = fence->next->element; // fence指向的是栅栏左边的最后一个元素 return true; } void print() const;};template <class Elem>bool LList<Elem>::insert(const Elem& item) { fence->next = new Link<Elem>(item, fence->next); if (tail == fence) tail = fence->next; rightcnt++; return true;}template <class Elem>bool LList<Elem>::append(const Elem& item) { tail = tail->next = new Link<Elem>(item, NULL); rightcnt++; return true;}template <class Elem> bool LList<Elem>::remove(Elem& it) { if (fence->next == NULL) return false; it = fence->next->element; Link<Elem>* ltemp = fence->next; fence->next = ltemp->next; if (tail == ltemp) tail = fence; delete ltemp; rightcnt--; return true;}template <class Elem> void LList<Elem>::prev() { Link<Elem>* temp = head; if (fence == head) return; while (temp->next != fence) temp = temp->next; fence = temp; leftcnt--; rightcnt++;}template <class Elem> bool LList<Elem>::setPos(int pos) { if ((pos < 0) || (pos > rightcnt + leftcnt)) return false; fence = head; for (int i = 0; i<pos; ++i) fence = fence->next; return true;}template <class Elem> void LList<Elem>::print() const { Link<Elem>* temp = head; cout<<"< "; while (temp != fence) { cout << temp->next->element << " "; temp = temp->next; } cout<< "| "; while (temp->next != NULL) { cout << temp->next->element << " "; temp = temp->next; } cout << ">\n"; }