zoukankan      html  css  js  c++  java
  • 2020-07-25:如何实现一个高效的单向链表逆序输出?

    福哥答案2020-07-25:

    1.链表反转。反转,输出,反转。
    2.递归。
    3.数组。遍历存数组,然后反向遍历数组。
    4.栈。遍历存栈,然后pop栈输出。

    golang代码采用第2种方法。代码如下:

    package test27_reverseprint
     
    import (
        "fmt"
        "testing"
    )
     
    //Definition for singly-linked list.
    type ListNode struct {
        Val  int
        Next *ListNode
    }
     
    //go test -v -test.run TestReversePrint
    func TestReversePrint(t *testing.T) {
        head := &ListNode{Val: 3, Next: &ListNode{Val: 1, Next: &ListNode{Val: 2}}}
     
        fmt.Println("正序输出--------------------")
        temp := head
        for temp != nil {
            fmt.Print(temp.Val, "	")
            temp = temp.Next
        }
     
        fmt.Println("
    
    反序输出--------------------")
        reversePrint(head)
     
    }
     
    func reversePrint(head *ListNode) {
        if head != nil {
            reversePrint(head.Next)
            fmt.Print(head.Val, "	")
        }
    }
    

      敲 go test -v -test.run TestReversePrint命令,结果如下:

  • 相关阅读:
    xml的建模
    P1341 无序字母对
    P1330 封锁阳光大学
    P2661 信息传递
    P1312 Mayan游戏
    P1514 引水入城
    C. Sad powers
    P1195 口袋的天空
    P1821 [USACO07FEB]银牛派对Silver Cow Party
    P1396 营救
  • 原文地址:https://www.cnblogs.com/waitmoon/p/13442943.html
Copyright © 2011-2022 走看看