单链表 创建 随意输入十个数 找出最大值 并输出
要求创建一个带头结点的单链表 并对这个链表施加一些操作
[解决办法]
- C/C++ code
using namespace std;// 结点类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>{ public: LList(int size) { 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(); int leftlength() const { return leftcnt; } int rightlength() const { return rightcnt; } bool setPos(int); bool getValue(Elem &) const; bool find(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; } }};// 向链表栅栏位置插入元素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> :: next(){ if (fence != tail) { fence = fence->next; rightcnt--; leftcnt++; }}// 使栅栏前移template<class Elem>void LList<Elem> :: prev(){ Link<Elem>* temp = head; if (fence = temp) 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 > leftcnt + rightcnt)) return false; fence = head; for (int i = 0; i < pos; i++) fence = fence->next; return true;}// 取出栅栏处的元素的值template<class Elem>bool LList<Elem> :: getValue(Elem &it) const{ if (rightcnt == 0) return false; it = fence->next->element; return true;}// 在链表中寻找元素template<class Elem>bool LList<Elem> :: find(Elem &it){ Elem item; for (setStart(); getValue(item); next()) if (it == item) return true; return false;}