一步一个脚印,弄懂吸收了,才是自己的知识
题目
输入:{1,2,3}
返回值:{3,2,1}
package main
type ListNode struct {
Val int
Next *ListNode
}
func ReverseList(pHead *ListNode) *ListNode {
// write code here
}
写法一:简单反转
func ReverseList(pHead *ListNode) *ListNode {
// write code here
if pHead == nil || pHead.Next == nil {
return pHead
}
var newHead *ListNode
for pHead != nil {
// 保存下一节点值
pNext := pHead.Next
// 反转节点赋值
// 当前元节点下一节点设值为反转节点
pHead.Next = newHead
// 反转节点等于当前元节点
newHead = pHead
// 下一节点作为下一次判断元节点
pHead = pNext
}
return newHead
}
写法二:反转+Go平行赋值
func ReverseList( pHead *ListNode ) *ListNode {
if pHead == nil || pHead.Next == nil{
return pHead
}
var newHead *ListNode
for pHead != nil {
pHead, pHead.Next, newHead = pHead.Next, newHead, pHead
}
return newHead
}
写法三:递归
func ReverseList(head *ListNode) *ListNode {
// write code here
if head == nil || head.Next == nil {
return head
}
res := ReverseList(head.Next)
head.Next.Next = head
head.Next = nil
return res
}