剑指Offer-Javascript版-从尾到头打印链表

对应LeetCode上的题目:面试题06. 从尾到头打印链表

题目描述:输入一个链表的头节点,从尾到头反过来打印出每个节点的值,链表节点定义如下:

1
2
3
4
function ListNode(val) {
this.val = val;
this.next = null;
}

题目描述

输入一个链表的头节点,从尾到头反过来打印出每个节点的值,链表节点定义如下:

1
2
3
4
function ListNode(val) {
this.val = val;
this.next = null;
}

解法一,使用栈

不改变链表的前提下。

遍历链表的顺序都是从头到尾,但是输出的顺序是从尾到头,也就是说第一个遍历的节点最后一个输出,最后一个遍历的节点第一个输出。这个不就是后进先出 吗?那么我们可以使用 来实现这种做法。

  • 每经过一个节点的时候,就把该节点放到一个栈中,当遍历完整个链表后。再从栈顶逐个输出节点的值
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

const printReverseListNode = (head) => {
if (!head) return []

// 栈用来存放已经遍历过的数组
const stack = []
let curNode = head

while(curNode) {
stack.push(curNode.val)

curNode = curNode.next
}

return stack.reverse()
}

可见,使用栈来解决这类问题,是非常的简单。但是我们也要熟知栈的各种概念,我们才能在解题的时候游刃有余,一点都不慌。

当然啦,我们也可以使用递归来实现这种解法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

const printReverseListNode = (head) => {
if (!head) return []
const stack =[]

const getReverseListNode = (head) => {
if(head) {
if(head.next !== null) {
printReverseListNode(head.next)
}
stack.push(head.val)
}
}

getReverseListNode(head)
return stack
}
# , 链表
You forgot to set the business and currency_code for Paypal. Please set it in _config.yml.
You forgot to set the url Patreon. Please set it in _config.yml.
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×