Sort List Solutions in Go
Number 148
Difficulty Medium
Acceptance 42.6%
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 sortList(head *ListNode) *ListNode {length := 0cur := headfor cur != nil {length++cur = cur.Next}if length <= 1 {return head}middleNode := middleNode1(head)cur = middleNode.NextmiddleNode.Next = nilmiddleNode = curleft := sortList(head)right := sortList(middleNode)return mergeTwoLists148(left, right)}func middleNode1(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}return p1}func mergeTwoLists148(l1 *ListNode, l2 *ListNode) *ListNode {if l1 == nil {return l2}if l2 == nil {return l1}if l1.Val < l2.Val {l1.Next = mergeTwoLists(l1.Next, l2)return l1}l2.Next = mergeTwoLists(l1, l2.Next)return l2}func mergeTwoLists(l1 *ListNode, l2 *ListNode) *ListNode {if l1 == nil {return l2}if l2 == nil {return l1}if l1.Val < l2.Val {l1.Next = mergeTwoLists(l1.Next, l2)return l1}l2.Next = mergeTwoLists(l1, l2.Next)return l2}