Reorder List Solutions in Go
Number 143
Difficulty Medium
Acceptance 37.3%
Link LeetCode
Solutions
Go solution by halfrost/LeetCode-Go
package leetcodeimport ("github.com/halfrost/LeetCode-Go/structures")// ListNode definetype ListNode = structures.ListNode/*** Definition for singly-linked list.* type ListNode struct {* Val int* Next *ListNode* }*/// 解法一 单链表func reorderList(head *ListNode) *ListNode {if head == nil || head.Next == nil {return head}// 寻找中间结点p1 := headp2 := headfor p2.Next != nil && p2.Next.Next != nil {p1 = p1.Nextp2 = p2.Next.Next}// 反转链表后半部分 1->2->3->4->5->6 to 1->2->3->6->5->4preMiddle := p1preCurrent := p1.Nextfor preCurrent.Next != nil {current := preCurrent.NextpreCurrent.Next = current.Nextcurrent.Next = preMiddle.NextpreMiddle.Next = current}// 重新拼接链表 1->2->3->6->5->4 to 1->6->2->5->3->4p1 = headp2 = preMiddle.Nextfor p1 != preMiddle {preMiddle.Next = p2.Nextp2.Next = p1.Nextp1.Next = p2p1 = p2.Nextp2 = preMiddle.Next}return head}// 解法二 数组func reorderList1(head *ListNode) *ListNode {array := listToArray(head)length := len(array)if length == 0 {return head}cur := headlast := headfor i := 0; i < len(array)/2; i++ {tmp := &ListNode{Val: array[length-1-i], Next: cur.Next}cur.Next = tmpcur = tmp.Nextlast = tmp}if length%2 == 0 {last.Next = nil} else {cur.Next = nil}return head}func listToArray(head *ListNode) []int {array := []int{}if head == nil {return array}cur := headfor cur != nil {array = append(array, cur.Val)cur = cur.Next}return array}