golang反转单链表
时间: 2024-03-19 12:39:08 浏览: 75
在Golang中,可以使用迭代或递归的方式来反转单链表。以下是两种实现方法:
1. 迭代法[^2]:
```go
type ListNode struct {
Val int
Next *ListNode
}
func reverseList(head *ListNode) *ListNode {
var prev *ListNode
curr := head
for curr != nil {
next := curr.Next
curr.Next = prev
prev = curr
curr = next
}
return prev
}
```
2. 递归法:
```go
type ListNode struct {
Val int
Next *ListNode
}
func reverseList(head *ListNode) *ListNode {
if head == nil || head.Next == nil {
return head
}
p := reverseList(head.Next)
head.Next.Next = head
head.Next = nil
return p
}
```
阅读全文