第五題 打印鏈表

轉(zhuǎn)自:http://blog.csdn.net/haijing1995/article/details/71492638

//棧
    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;

        //在結(jié)尾插入元素
        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++;
        };

        //從尾到頭打印節(jié)點(diǎn)
        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());

運(yùn)行結(jié)果:
![圖片.png](http://upload-images.jianshu.io/upload_images/5623231-84843bfe74ab5bed.png?imageMogr2/auto-orient/strip%7CimageView2/2/w
/1240)

完整的打印一遍鏈表(添加刪除等方法):
https://www.bbsmax.com/A/1O5E88LrJ7/

題目描述
輸入一個(gè)鏈表,從尾到頭打印鏈表每個(gè)節(jié)點(diǎn)的值。

從尾到頭打印鏈表:
方法一:

/*function ListNode(x){
    this.val = x;
    this.next = null;
}*/
function printListFromTailToHead(head)
{
    // write code here
    rs = []
    if (head == null){
        return rs;
    }else{
        l = head;
        while (l.next != null)
        {
            rs.push(l.val);
            l = l.next;
        }
        rs.push(l.val);
        return rs.reverse()
    }
}

方法二:

function printListFromTailToHead(head)
{
    // write code here
    var arr = []
    while(head) {
        arr.unshift(head.val)
        head = head.next
    }
    return arr
}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容