经典算法:排序链表
题目:148. 排序链表
给你链表的头结点 head
,请将其按 升序 排列并返回 排序后的链表。
示例 1:
输入:head = [4,2,1,3]
输出:[1,2,3,4]
示例 2:
输入:head = [-1,5,3,4,0]
输出:[-1,0,3,4,5]
示例 3:
输入:head = []
输出:[]
提示:
- 链表中节点的数目在范围 [0, $ 5 * 10^4 $] 内
- $ -10^5 $ <= Node.val <= $ 10^5 $
进阶: 你可以在 $ O(n log n) $ 时间复杂度和常数级空间复杂度下,对链表进行排序吗?
解题思路
见代码。
实现代码
package leetcodeimport ("sort""github.com/superproj/go-leetcode/structure"
)// ListNode define
type ListNode = structure.ListNode/*** Definition for singly-linked list.* type ListNode struct {* Val int* Next *ListNode* }*/
func sortList(head *ListNode) *ListNode {// 将链表转换成slicenums := make([]int, 0)tmp := headfor tmp != nil {nums = append(nums, tmp.Val)tmp = tmp.Next}// 将slice排序sort.Ints(nums)// 将slice转换成链表dummyHead := new(ListNode)node := dummyHeadfor i := 0; i < len(nums); i++ {tmpNode := &ListNode{nums[i], nil}node.Next = tmpNodenode = tmpNode}return dummyHead.Next
}
单元测试
package leetcodeimport ("testing""github.com/stretchr/testify/assert""github.com/superproj/go-leetcode/structure"
)func Test_sortList(t *testing.T) {assert := assert.New(t)type args struct {first []int}tests := []struct {args argswant []int}{{args: args{[]int{1, 2, 3, 4, 5}},want: []int{1, 2, 3, 4, 5},},{args: args{[]int{1, 1, 2, 5, 5, 4, 10, 0}},want: []int{0, 1, 1, 2, 4, 5, 5, 10},},{args: args{[]int{1}},want: []int{1},},{args: args{[]int{}},want: []int{},},}for _, tt := range tests {first := structure.Ints2List(tt.args.first)actual := structure.List2Ints(sortList(first))assert.Equal(tt.want, actual)}
}