剑指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
}
这篇博客介绍了两种方法在Golang中实现从尾到头打印链表。第一种方法是先遍历链表将节点值存入数组,然后反转数组;第二种方法则是直接统计节点数量,反向遍历链表进行赋值。提供了详细的代码实现,适用于理解链表操作和数组反转技巧。

556

被折叠的 条评论
为什么被折叠?



