本文主要是介绍leetcode 206. 反转链表 go 语言实现,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
递归实现与非递归实现,以及头插法
/*** @Description: 反转链表 非递归方式** @Date:* @Author: fuGuoWen* @Return* @Throws*/
func reverseList(head *ListNode) *ListNode {var pre *ListNodevar next *ListNodefor head != nil {next = head.Nexthead.Next = prepre = headhead = next}return pre
}/*** @Description: 反转链表 递归方式** @Date:* @Author: fuGuoWen* @Return* @Throws*/
func reverseList2(head *ListNode) *ListNode {if head == nil || head.Next == nil {return head}next := head.Nextpre := reverseList2(next)next.Next = headhead.Next = nilreturn pre
}/*** @Description: 头插法反转链表* * @Date: * @Author: fuGuoWen* @Return * @Throws */
func reverseList3(head *ListNode) *ListNode {temp := ListNode{0, nil}temp.Next = headpre := tempq := temp.Nextfor head != nil {remove := q.Nextq.Next = q.Next.Nextremove.Next = pre.Nextpre.Next = removehead = head.Next}return temp.Next
}
这篇关于leetcode 206. 反转链表 go 语言实现的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!