实验四 顺序栈、链栈(JavaScript)

来源:互联网 发布:饭店排号软件 编辑:程序博客网 时间:2024/05/18 01:57

实验四   顺序栈、链栈(JavaScript)


实验目的

熟练掌栈的结构特点,掌握栈的顺序存储和链式存储结构和实现。


实验内容

自己确定结点的具体数据类型和问题规模:

分别建立一个顺序栈和链栈,实现栈的压栈和出栈操作。


实验步骤

顺序栈

顺序栈必须确定一个固定长度。

function StackSize(count) {  this.arr = new Array();  var top = -1; //定义一个头指针  if (count != undefined) {    this.count = count;    this.arr = new Array(this.count);  } else {    this.count = 0;  }
  //入栈操作  this.Push = function (valve) {    if (top == this.count) {      return false;    } else {      this.arr[++top] = valve;      return true;    }    return false;  }
  //显示栈内元素  this.Show = function () {    for (var i = 0; i < this.arr.length; i++) {      console.log(this.arr[i]);    }  }
  //弹栈操作  this.Pop=function(){    if(top==-1){      return false;    }else{      var remove=this.arr[top];      this.arr[top]=null;  //清除栈顶元素,相当于删除      top--;      return remove;    }  }}
//测试代码StackSize(3);this.Push(1);this.Push(2);this.Push(3);this.Show();this.Pop();this.Show();
实验结果

入栈实验结果


弹栈实验结果



链栈

链栈没有栈满的问题,只有当内存没有可用空间时才会出现栈满,但是每个元素都需要一个指针域,从而产生了结构性开销。

function StackSize() {  this.top = null; //定义一个头指针}
//定义一个List来存放所有方法var List =function(){  function Node(newdata) {    this.data = newdata;    this.next = null;  }  
  //入栈操作  this.Push = function (value) {    var node=new Node(value);    node.next=this.top;    this.top=node;  }  
  //出栈操作  this.Pop=function(data){    if(top==null){      console.log("栈空");    }else{      var node=this.top;      this.top=node.next;      return node;    }  }
  //获取栈顶元素  this.Gettop=function(){    if(this.top==null){      console.log("栈空");    }else{      return this.top.data;    }  }}
//测试代码var list=new List();list.Push(1);list.Push(2);list.Push(3);console.log(list.Gettop());console.log(list.Pop());

实验结果



原创粉丝点击