鍍金池/ 問答/HTML/ js小白求問

js小白求問

這個方法是輸入一個鏈表,然后從尾到頭打印鏈表

    function ListNode(x){
        this.val = x;
        this.next = null;
    }
    function printListFromTailToHead(head)
    {
        // write code here
        var arr = [];
        while(head != null) {
            // var a = head.val;
            // console.log(a);
            arr.unshift(head.val);
            head = head.next;
        }
        return arr;
    }
    
1怎么調(diào)用才能實現(xiàn)從尾到頭打印的功能
2為什么這樣調(diào)用printListFromTailToHead(1,2,3)返回的是下圖中的

clipboard.png

回答
編輯回答
愛是癌
  1. 參數(shù)要求傳輸?shù)氖擎湵淼牡谝粋€元素,故需要這么創(chuàng)建鏈表后,然后再調(diào)用打印鏈表的方法

    var head = new ListNode(1);
    var second = new ListNode(2);
    var third = new ListNode(3);
    
    head.next = second; 
    second.next = third;
    
    printListFromTailToHead(head);  // [3, 2, 1]
  2. printListFromTailToHead要求傳入一個鏈表對象,你傳入3個數(shù)值,肯定會不能符合你的預(yù)期,因為數(shù)值沒有val和next屬性(返回undefined)。
2017年7月27日 09:21