链表-从尾到头打印链表

121 阅读1分钟

剑指 Offer 06. 从尾到头打印链表

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

示例 1:

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

题解1:递归 时间O(N)、空间O(N)

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} head
 * @return {number[]}
 */
var reversePrint = function(head) {
    const stack = []
    const getNext = (node) =>{
        if(!node) return
        stack.push(node.val) // 可利用回溯添加,后面则不需要反转
        if(node.next){
            getNext(node.next)
        }
        // 利用回溯
        //stack.push(node.val)
    }
    getNext(head)
    return stack.reverse() 
    // 利用回溯
    //return stack
};

题解2:时间和空间占用较高

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} head
 * @return {number[]}
 */
var reversePrint = function(head) {
    return head === null ? [] : reversePrint(head.next).concat(head.val)
};

题解3: 非递归

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} head
 * @return {number[]}
 */
var reversePrint = function(head) {
    const nodes = []
    while(head){
        nodes.push(head.val)
        head = head.next
    }
    return nodes.reverse()
};

规则:

ListNode为节点对象,val为值,next指向下一个节点的地址

题目来源:LeetCode