package main
import "fmt"
type ListNode struct {
Val int
Next *ListNode
}
func reverseList(head *ListNode) *ListNode {
if head == nil || head.Next == nil {
return head
}
newHead := reverseList(head.Next)
head.Next.Next = head
head.Next = nil
return newHead
}
func main() {
// 创建一个链表: 1 -> 2 -> 3 -> 4 -> 5
head := &ListNode{Val: 1}
temp := head
for i := 2; i <= 5; i++ {
temp.Next = &ListNode{Val: i}
temp = temp.Next
}
// 翻转链表
newHead := reverseList(head)
// 打印翻转后的链表: 5 -> 4 -> 3 -> 2 -> 1
for newHead != nil {
fmt.Print(newHead.Val, " -> ")
newHead = newHead.Next
}
fmt.Println()
}
标签:head,ListNode,nil,反转,newHead,链表,Next
From: https://www.cnblogs.com/qcy-blog/p/18156825