单链表 创建 随意输入十个数 找出最大值 并输出
时间:2011-12-18
来源:互联网
要求创建一个带头结点的单链表 并对这个链表施加一些操作
作者: yizhicainiao2 发布时间: 2011-12-18
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; }
作者: Johnkey_Chen 发布时间: 2011-12-19
相关阅读 更多
热门阅读
-
office 2019专业增强版最新2021版激活秘钥/序列号/激活码推荐 附激活工具
阅读:74
-
如何安装mysql8.0
阅读:31
-
Word快速设置标题样式步骤详解
阅读:28
-
20+道必知必会的Vue面试题(附答案解析)
阅读:37
-
HTML如何制作表单
阅读:22
-
百词斩可以改天数吗?当然可以,4个步骤轻松修改天数!
阅读:31
-
ET文件格式和XLS格式文件之间如何转化?
阅读:24
-
react和vue的区别及优缺点是什么
阅读:121
-
支付宝人脸识别如何关闭?
阅读:21
-
腾讯微云怎么修改照片或视频备份路径?
阅读:28