剑指Offer06.从尾到头打印链表Golang版
1. 问题描述
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2]
输出:[2,3,1]
2. 思路
思路1
- 遍历链表,把结果存到数组中,
- 反转数组
思路2
- 遍历链表,统计出节点的数量
- 反向遍历数组,进行赋值
3. 代码
3.1. 思路1代码
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func reversePrint(head *ListNode) []int {
cur := head
res := []int{}
for cur != nil {
res = append(res, cur.Val)
cur = cur.Next
}
for i := 0; i < len(res) / 2; i++ {
res[i],res[len(res) - 1 - i] = res[len(res) - 1 - i], res[i]
}
return res
}
思路2代码
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func reversePrint(head *ListNode) []int {
cur := head
count := 0
for cur != nil {
count++
cur = cur.Next
}
cur = head
res := make([]int,count)
for i := count - 1; i >= 0; i-- {
res[i] = cur.Val
cur = cur.Next
}
return res
}