面试题5:从头到尾打印链表

剑指Offer面试题5:从头到尾打印链表(JS实现)

题目描述:输入一个链表的头结点,从头到尾反过来打印出每个结点的值。
    //栈
    function Stack() {
        var arr = [];
        this.push = function(element) {
            arr.push(element);
        };
        this.pop = function(){
            return arr.pop();
        };
        this.isEmpty = function() {
            return arr.length === 0;
        }
    }

    function LinkList() {
        var Node = function(element) {
            this.element = element;
            this.next = null;
        }
        length = 0;
        var head = null;

        //在结尾插入元素
        this.append = function(element) {
            var node = new Node(element),
                current;
            if(head === null) {
                head = node;
            }else {
                current = head;
                while(current.next) {
                    current = current.next;
                }
                current.next = node;
            }
            length++;
        };

        //从尾到头打印节点
        this.PrintListReversingly = function(){
            var stack = new Stack(),
                current = head,
                str = '';
            while(current) {
                stack.push(current.element);
                current = current.next;
            }
            while(!stack.isEmpty()){
                str += stack.pop();
            }
            return str;
        }
    };

    var list = new LinkList();
    list.append(15);
    list.append(10);
    list.append(8);
    list.append(6);
    list.append(3);
    console.log(list.PrintListReversingly());
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值