Skip to content

Latest commit

 

History

History
42 lines (37 loc) · 901 Bytes

06.md

File metadata and controls

42 lines (37 loc) · 901 Bytes

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

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

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

这个题目还是比较自由的。 可以先反转链表(剑指24题)然后打印 或者按照原顺序打印 然后反转数组,建议都试一下

反转数组做法:

var reversePrint = function(head) {
    let res = []
    let p1 = head;
    while(p1) {
        res.push(p1.val)
        p1 = p1.next
    }
    return res.reverse()
};

反转链表再放入数组

var reversePrint = function(head) {
    let p1 = head;
    let p2 = null;
    while(p1) {
        const next = p1.next
        p1.next = p2
        p2 = p1
        p1 = next
    }
    let arr = []
    while(p2) {
        arr.push(p2.val)
        p2 = p2.next
    }
    return arr
}