本文主要是介绍Golang | Leetcode Golang题解之第148题排序链表,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目:
题解:
func merge(head1, head2 *ListNode) *ListNode {dummyHead := &ListNode{}temp, temp1, temp2 := dummyHead, head1, head2for temp1 != nil && temp2 != nil {if temp1.Val <= temp2.Val {temp.Next = temp1temp1 = temp1.Next} else {temp.Next = temp2temp2 = temp2.Next}temp = temp.Next}if temp1 != nil {temp.Next = temp1} else if temp2 != nil {temp.Next = temp2}return dummyHead.Next
}func sortList(head *ListNode) *ListNode {if head == nil {return head}length := 0for node := head; node != nil; node = node.Next {length++}dummyHead := &ListNode{Next: head}for subLength := 1; subLength < length; subLength <<= 1 {prev, cur := dummyHead, dummyHead.Nextfor cur != nil {head1 := curfor i := 1; i < subLength && cur.Next != nil; i++ {cur = cur.Next}head2 := cur.Nextcur.Next = nilcur = head2for i := 1; i < subLength && cur != nil && cur.Next != nil; i++ {cur = cur.Next}var next *ListNodeif cur != nil {next = cur.Nextcur.Next = nil}prev.Next = merge(head1, head2)for prev.Next != nil {prev = prev.Next}cur = next}}return dummyHead.Next
}
这篇关于Golang | Leetcode Golang题解之第148题排序链表的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!