出于对数据结构的喜欢以及对前端web技术的热爱,本人开始推出一个用JavaScipt描述数据结构的序列,望大家海量指点纠正,在此感激不尽。
首先是用JS编写线性表的顺序存储结构,以下附上代码:
- /**
- * 线性表之顺序存储结构
- */
- var len = 50; //顺序存储线性表的数组结构大小
- function SeqList(){
- this.data = new Array(len);
- this.currentLength = 0; //线性表当前长度
- this.countNum = function(){
- while(typeof this.data[this.currentLength] != "undefined"){
- this.currentLength++;
- }
- };
- }
- //添加元素,此处单纯的往数组尾部添加元素,不涉及元素的移动
- SeqList.prototype.addElement = function(data){
- this.data[this.currentLength] = data;
- this.countNum();
- };
- //在指定位置添加元素,并且移动相关元素,index表示第几个位置,不包括0
- SeqList.prototype.addElementByIdx = function(data,index){
- if(index > this.currentLength){
- return "WrongIndexBound";
- }
- for(var i = this.currentLength-1 ; i >= index-1 ; i--){
- this.data[i+1] = this.data[i];
- }
- this.data[index-1] = data;
- this.countNum();
- return "Success!!";
- };
- var e ; //存储返回的值
- SeqList.prototype.getElement = function(index){
- e = this.data[index]; //可不可以返回全局变量啊?
- if(typeof e == "undefined"){
- return "Wrong index";
- }
- else{
- return e;
- }
- };
- var countMember = 0; //统计参量
- function Member(name,age){
- this.name = name;
- this.age = age;
- this.toString = function(){
- return "[" + this.name + "," + this.age + "]";
- };
- }
- var itmArray = new Array();
- //驱动程序
- function driver(){
- var mySeqList = new SeqList();
- var itm1 = new Member("zero",30);
- countMember++; //易错提示:当写入一个属性的值时候,JS不会使用原型对象
- itmArray[0] = itm1;
- var itm2 = new Member("one",20);
- countMember++;
- itmArray[1] = itm2;
- var itm3 = new Member("two",10);
- countMember++;
- itmArray[2] = itm3;
- var itm4 = new Member("three",40);
- countMember++;
- itmArray[3] = itm4;
- var tempItm = new Member("TEMPITEM",140);
- /*for(var j = 0; j < 20; j++){
- }*/
- for(var z =0; z < countMember; z++){ //添加元素
- document.writeln(itmArray[z]);
- mySeqList.addElement(itmArray[z]);
- }
- var tempppp = mySeqList.getElement(2);
- document.writeln(tempppp + "<br />");
- document.write(e + "<br />");
- //循环遍历,注意作用域的问题
- var iii = mySeqList.addElementByIdx(tempItm, 3);
- document.write("iii = " + iii + "<br />");
- document.writeln("mySeqList.getElement(2) = " + mySeqList.getElement(2)+ "<br />");
- document.write("循环遍历顺序表" + "<br />");
- for(var f = 0; f < mySeqList.currentLength; f++ ){
- document.write(mySeqList.data[f] + "<br />");
- }
- }
- driver();