从尾到头打印链表(简单) yinshibanxian

一、题目描述

输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。

示例:

输入:head = [1,3,2]
输出:[2,3,1]

限制

0 <= 链表长度 <= 10000

二、题目解析

  1. 遍历链表法

    对链表进行遍历,将遍历到的每个链表节点的值unshift到结果数组中,返回结果数组即可.

     /**
     * Definition for singly-linked list.
     * function ListNode(val) {
     *     this.val = val;
     *     this.next = null;
     * }
     */
     /**
     * @param {ListNode} head
     * @return {number[]}
     */
     var reversePrint = function(head) {
         const result = [];
         if(head == null) return result;
         let current = head;
         while(current != null) {
             result.unshift(current.val);
             current = current.next;
         }
         return result;
     };
    
    • 时间复杂度: O(n)
    • 空间复杂度: O(n)

来源:力扣(LeetCode)

链接:https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof