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

361 阅读1分钟

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

题意

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

image.png

解法

这里输出是以数组的形式返回。首先是顺序遍历+反序输出。这里的反序输出可以有三种做法。

1. 遍历加数组反转

先顺序遍历链表将链表元素加入数组中,最后再反转数组。

2. 利用辅助栈实现反转

先顺序遍历链表将链表元素加入栈中,然后再将栈元素出栈到数组中返回。

3. 利用递归来实现反序输出

将当前节点的值作为数组的最后一个元素,将后面节点的值拼接到当前节点的值的前面。

代码

1. 遍历加数组反转

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

2. 利用辅助栈实现反转

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} head
 * @return {number[]}
 */
var reversePrint = function(head) {
    let p = head
    let stack = []
    let res = []
    if(!head)return res
    while(p){
        stack.push(p.val)
        p = p.next
    }
    while(stack.length>0){
        res.push(stack.pop())
    }
    return res
};

3. 利用递归来实现反序输出

/**
 * 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)
};