实现循环链表(js实现)
2015-10-22 00:17
537 查看
循环链表与单链表结构基本相似,唯一不同就是单链表的尾节点的next属性指向null,然而循环链表的尾节点的next属性指向首节点,这样就构成了一个循环
// 定义构造函数 function createNode(data,next) { var obj = { data: data, next: next }; return obj; } // 定义链表函数 function Lists() { this.pRear = null; this.length = 0; this.InsertAtEnd = function (data) { if (this.length == 0) { var node = new createNode(data,this.pRear); this.pRear = node; node.next = this.pRear; } else { var node = new createNode(data,this.pRear.next); this.pRear.next = node; this.pRear = node; } this.length++; } this.InsertAtFirst = function (data) { if (this.length == 0) { var node = new createNode(data,this.pRear); this.pRear = node; node.next = this.pRear; } else { var node = new createNode(data,this.pRear.next); this.pRear.next = node; } this.length++; } this.Locate = function (index) { if (index < 0 || index > this.length - 1) { throw new Error("索引值有错"); } var temp = this.pRear.next; for (var i = 0; i < index; i++) { temp = temp.next; } return temp; } this.Insert = function (index,data) { if (index < 0 || index > this.length) { throw new Error("索引值有错"); } if (index == 0) { this.InsertAtFirst(data); } else if (index == this.length) { this.InsertAtEnd(data); } else { var node = new createNode(data,this.Locate(index)); this.Locate(index - 1).next = node; this.length++; } } this.Search = function (data) { var temp = this.pRear.next; for (var i = 0; i < this.length; i++) { if (data == temp.data) { return i; } temp = temp.next; } return -1; } this.Clear = function () { this.length = 0; this.pRear = null; } this.Remove = function (index) { if (index < 0 || index > this.length - 1 || this.length == 0) { throw new Error("索引值有错"); } if (this.length == 1) { this.Clear(); return 1; } if (index == 0) { this.pRear.next = this.Locate(0).next; } else { this.Locate(index - 1).next = this.Locate(index).next; } } this.isEmpty = function () { return this.length == 0 ? true : false; } this.toString = function () { var temp = this.pRear.next, str = ""; for (var i = 0; i < this.length; i++) { str += "第" + i + "个为:" + temp.data; temp = temp.next; } return str; } } // 测试 var list = new Lists(); list.Insert(0,1); list.InsertAtFirst(0); list.Insert(2,-1); list.InsertAtEnd(20); console.log(list.Search(2)); console.log(list.isEmpty()); console.log(list.toString());
相关文章推荐
- Ember.js 入门指南——元数据
- JSP页面文件中base标记用法实例分析
- 比较全面的C 、Java、JavaScript中的正则表达式详解
- JS+CSS实现仿msn风格选项卡效果代码
- JS+CSS实现大气清新的滑动菜单效果代码
- JS实现新浪博客左侧的Blog管理菜单效果代码
- JS实现不使用图片仿Windows右键菜单效果代码
- JS+CSS实现的竖向简洁折叠菜单效果代码
- 浅析JavaScript 调试方法和技巧
- js检测用户输入密码强度
- js显示当前日期时间和星期几
- 编写高质量JavaScript代码
- 浅谈 JS 创建对象的 8 种模式
- JS 实现简单的页面局部打印例子
- js操作cookie
- js获取url参数值
- JSP/Servlet-----web.xml配置
- Ember.js 入门指南——元数据
- 超链接标签绑定JS事件&&不加"javascript:;"导致的杯具
- 使用JSONP解决跨域问题-代码示例