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

来源:互联网 发布:美国种族歧视华人 知乎 编辑:程序博客网 时间:2024/05/21 08:41

剑指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());
0 0
原创粉丝点击