反转链表
func revoert_linklist(pHead *ListNode) *ListNode {
var newHead,temp *ListNode
for pHead != nil {
// 赋值头head到临时节点
temp = pHead
// pHead移到了下一位
pHead = pHead.Next
// 对新链表做头插
temp.Next = newHead
// newHead前移动,准备下一次循环
newHead = temp
}
return newHead
}
测试
link1 := &ListNode{}
link1.Val = 1
link2 := &ListNode{}
link2.Val = 2
link3 := &ListNode{}
link3.Val = 3
link4 := &ListNode{}
link4.Val = 4
link5 := &ListNode{}
link5.Val = 5
link1.Next = link2
link2.Next = link3
link3.Next = link4
link4.Next = link5
fmt.Println(link1)
pre :=revoert_linklist(link1)
fmt.Println(pre.Val)
fmt.Println(pre.Next.Val)
fmt.Println(pre.Next.Next.Val)
return
&{1 0xc42016c600}
5
4
3
有疑问加站长微信联系(非本文作者)