LeetCode 剑指 Offer 06. 从尾到头打印链表
题目描述
思路分析
思路描述
参考代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
func reversePrint(head *ListNode) []int {
stack := []int{}
for head != nil {
stack = append(stack, head.Val)
head = head.Next
}
var res []int
for len(stack) > 0 {
res = append(res, stack[len(stack)-1])
stack = stack[:len(stack)-1]
}
return res
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
func reverseBookList(head *ListNode) []int {
head = reverse(head)
var res []int
cur := head
for cur != nil {
res = append(res, cur.Val)
cur = cur.Next
}
return res
}
func reverse(head *ListNode) *ListNode {
if head == nil || head.Next == nil {
return head
}
var pre *ListNode
cur := head
for cur != nil {
next := cur.Next
cur.Next = pre
pre = cur
cur = next
}
return pre
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
func reverseBookList(head *ListNode) []int {
var res []int
var dfs func(node *ListNode)
dfs = func(node *ListNode) {
if node == nil {
return
}
dfs(node.Next)
res = append(res, node.Val)
}
dfs(head)
return res
}
1
write your code here
CC BY-NC-SA 4.0
许可协议,转载请注明出处!
本博客所有文章除特别声明外,均采用