您的位置:首页 > 汽车 > 时评 > Golang | Leetcode Golang题解之第148题排序链表

Golang | Leetcode Golang题解之第148题排序链表

2024/11/17 0:36:57 来源:https://blog.csdn.net/weixin_66442839/article/details/139640432  浏览:    关键词: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
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com