Js rookie asks questions

this method is to enter a linked list and then print the linked list from end to end

    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
2printListFromTailToHead(1,2,3)

clipboard.png

Apr.07,2021

  1. The

    parameter requires that the first element of the linked list be transferred, so you need to create the linked list in this way, and then call the method of printing the linked list

    .
    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 requires you to pass in a linked list object. If you pass in three values, it will certainly not meet your expectations, because the values do not have val and next attributes (return undefined).
Menu