/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/funcreverseList(head*ListNode)*ListNode{ifhead==nil||head.Next==nil{returnhead}varprev*ListNodecur:=headforcur!=nil{next:=cur.Nextcur.Next=prevprev=curcur=next}returnprev}
解法二:递归
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/funcreverseList(head*ListNode)*ListNode{ifhead==nil||head.Next==nil{returnhead}newHead:=reverseList(head.Next)head.Next.Next=headhead.Next=nilreturnnewHead}