面试题06. 从尾到头打印链表

image.png

  1. package main
  2. import "fmt"
  3. type ListNode struct {
  4. Val int
  5. Next *ListNode
  6. }
  7. func reversePrint(head *ListNode) []int {
  8. stack :=make([]*ListNode,0)
  9. for head!=nil{
  10. stack = append(stack,head)
  11. head =head.Next
  12. }
  13. var res []int
  14. for len(stack)>0{
  15. node :=stack[len(stack)-1]
  16. res = append(res,node.Val)
  17. stack = stack[:len(stack)-1]
  18. }
  19. return res
  20. }
  21. func main() {
  22. one :=&ListNode{Val:1}
  23. three :=&ListNode{Val:3}
  24. one.Next = three
  25. two :=&ListNode{Val:2}
  26. three.Next=two
  27. fmt.Println(reversePrint(one))
  28. }

image.png