用JS实现链表结构

  大家好,今天抽空用JS写了点东西。因为今天体测了,我看到了一个我熟悉的背景。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>栈结构</title>
</head>
<body>
    <script>
        function  Stack(){
            this.items=[];
            //进栈操作
            Stack.prototype.push=function(element){
                this.items.push(element);
            }
            //出栈操作
            Stack.prototype.pop=function(){
                return this.items.pop();
            }
            //查看栈顶元素
            Stack.prototype.peek=function(){
                return this.items[this.items.length-1];
            }
            //查看栈是否为空
            Stack.prototype.isEmpty=function(){
                return this.items.length==0;
            }
            //打印栈
            Stack.prototype.toString=function(){
                var resultString='';
                for(var i=0;i<this.items.length;i++){
                    resultString+=this.items[i]+' ';
                }
                return resultString;
            }
        }
        //创建一个栈对象
        var s=new Stack();
        //向栈中压入元素
        s.push(1);
        s.push(2);
        s.push(4);
        s.push(5);
        s.push(6);
        //打印结果
        alert(s);
        //弹出一个元素再添加一个元素
        s.pop();
        s.push(7);
        //打印结果
        alert(s);
        //打印结果
        alert(s.isEmpty());
    </script>

</body>
</html>

运行结果:

1.向栈中添加元素[1,2,4,5,6]

 

2.栈弹出一个元素,再添加一个新的元素7

 

3.判断此时的栈是否为空

 

 我就写了这些可能少了点吧。不过还好啦。

 

 

posted @ 2019-11-17 21:33  苹果&桃子  阅读(420)  评论(0)    收藏  举报