Skip to content

Instantly share code, notes, and snippets.

@alldroll
Created February 27, 2020 16:49
Show Gist options
  • Select an option

  • Save alldroll/a5dbb4afc4c7746d4ac6c818d6ff6d55 to your computer and use it in GitHub Desktop.

Select an option

Save alldroll/a5dbb4afc4c7746d4ac6c818d6ff6d55 to your computer and use it in GitHub Desktop.
// https://leetcode.com/problems/sort-list
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func sortList(head *ListNode) *ListNode {
if head == nil || head.Next == nil {
return head
}
middle := splitList(head)
return merge(sortList(head), sortList(middle))
}
func splitList(head *ListNode) *ListNode {
var prev *ListNode
hare := head
tortoise := head
for hare != nil && hare.Next != nil {
hare = hare.Next.Next
prev = tortoise
tortoise = tortoise.Next
}
prev.Next = nil
return tortoise
}
func merge(a, b *ListNode) (result *ListNode) {
if a == nil {
return b
}
if b == nil {
return a
}
if a.Val < b.Val {
a.Next = merge(a.Next, b)
result = a
} else {
b.Next = merge(a, b.Next)
result = b
}
return
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment