要實(shí)現(xiàn)golang鏈表的反轉(zhuǎn),可以采用迭代的方式或者遞歸的方式。
迭代方式的代碼如下:
type ListNode struct {
Val int
Next *ListNode
}
func reverseList(head *ListNode) *ListNode {
var prev *ListNode // 上一個(gè)節(jié)點(diǎn)
curr := head // 當(dāng)前遍歷的節(jié)點(diǎn)
for curr != nil {
next := curr.Next // 保存下一個(gè)節(jié)點(diǎn)
curr.Next = prev // 將當(dāng)前節(jié)點(diǎn)的Next指向上一個(gè)節(jié)點(diǎn)
prev = curr // 更新上一個(gè)節(jié)點(diǎn)為當(dāng)前節(jié)點(diǎn)
curr = next // 更新當(dāng)前節(jié)點(diǎn)為下一個(gè)節(jié)點(diǎn)
}
return prev // 返回反轉(zhuǎn)后的頭節(jié)點(diǎn)
}
遞歸方式的代碼如下:
type ListNode struct {
Val int
Next *ListNode
}
func reverseList(head *ListNode) *ListNode {
if head == nil || head.Next == nil {
return head
}
newHead := reverseList(head.Next) // 先反轉(zhuǎn)后面的鏈表
head.Next.Next = head // 將當(dāng)前節(jié)點(diǎn)的下一個(gè)節(jié)點(diǎn)的Next指向當(dāng)前節(jié)點(diǎn),實(shí)現(xiàn)反轉(zhuǎn)
head.Next = nil // 將當(dāng)前節(jié)點(diǎn)的Next置為nil,防止形成環(huán)
return newHead // 返回新的頭節(jié)點(diǎn)
}
以上代碼實(shí)現(xiàn)了golang鏈表的反轉(zhuǎn),分別采用了迭代和遞歸兩種方式。