题目
输入 1->2->3->4->null输出 5->4->3->2->1->null
思路
思路 把指针指向前一个元素,后边的不断向前移动,并改变方向
pre 就是cur的最前边的那位(pre=cur)
cur就是当前元素后面链表元素(cur=cur.Next)
cur.Next肯定是pre(curl.Next=pre)原因是cur赋值给了pre
过程
![在这里插入图片描述](https://img.php1.cn/3cd4a/1eebe/cd5/0ef126b5295c089b.webp)
![在这里插入图片描述](https://img.php1.cn/3cd4a/1eebe/cd5/70be2ca197098d98.webp?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzM5Nzg3MzY3,size_16,color_FFFFFF,t_70)
代码
type ListNode struct {Val intNext *ListNode
}
func reversListTwo(head *ListNode)*ListNode{if head == nil || head.Next == nil{return head}pre := reversListTwo(head.Next)head.Next.Next = headhead.Next = nilreturn pre
}
func reversList(head *ListNode)*ListNode{cur := headvar pre *ListNode = nilfor cur != nil{pre ,cur ,cur.Next = cur,cur.Next,pre}return pre
}func main(){head := new(ListNode)head.Val = 1ln2 := new(ListNode)ln2.Val = 2ln3 := new(ListNode)ln3.Val = 3ln4 := new(ListNode)ln4.Val = 4ln5 := new(ListNode)ln5.Val = 5head.Next = ln2ln2.Next = ln3ln3.Next = ln4ln4.Next = ln5pre := reversList(head)fmt.Printf("%#v\n",pre)fmt.Printf("%#v\n",pre.Next)fmt.Printf("%#v\n",pre.Next.Next)fmt.Printf("%#v\n",pre.Next.Next.Next)fmt.Printf("%#v\n",pre.Next.Next.Next.Next)fmt.Printf("%#v\n",pre.Next.Next.Next.Next.Next)}
验证
&main.ListNode{Val:5, Next:(*main.ListNode)(0xc000104210)}
&main.ListNode{Val:4, Next:(*main.ListNode)(0xc000104200)}
&main.ListNode{Val:3, Next:(*main.ListNode)(0xc0001041f0)}
&main.ListNode{Val:2, Next:(*main.ListNode)(0xc0001041e0)}
&main.ListNode{Val:1, Next:(*main.ListNode)(nil)}
(*main.ListNode)(nil)