Golang程序 逆转给定的链表
例子
解决这个问题的方法
第1步 - 定义一个方法,接受一个链表的头部。
第2步 - 如果 head == nil,返回;否则,调用 ReverseLinkedList ,递归。
第3步 - 在最后打印 head.value 。
例子
package main
import "fmt"
type Node struct {
value int
next *Node
}
func NewNode(value int, next *Node) *Node{
var n Node
n.value = value
n.next = next
return &n
}
func TraverseLinkedList(head *Node){
fmt.Printf("Input Linked List is: ")
temp := head
for temp != nil {
fmt.Printf("%d ", temp.value)
temp = temp.next
}
fmt.Println()
}
func ReverseLinkedList(head *Node){
if head == nil{
return
}
ReverseLinkedList(head.next)
fmt.Printf("%d ", head.value)
}
func main(){
head := NewNode(30, NewNode(10, NewNode(40, NewNode(40, nil))))
TraverseLinkedList(head)
fmt.Printf("Reversal of the input linked list is: ")
ReverseLinkedList(head)
}
输出
Input Linked List is: 30 10 40 40
Reversal of the input linked list is: 40 40 10 30