合并两个有序链表

48 阅读1分钟

方法一

把链表转换为切片,切片合并并排序,再把切片转换为链表

func mergeTwoLists(list1 *ListNode, list2 *ListNode) *ListNode {
	slice1 := toSlice(list1)
	slice2 := toSlice(list2)
	//切片合并排序
	slice := append(slice1, slice2...)
	sort.Ints(slice)
	return toListNode(slice)
}

func toSlice(list *ListNode) []int {
	var slice []int
	node := list
	for node != nil {
		slice = append(slice, node.Val)
		node = node.Next
	}
	return slice
}

func toListNode(slice []int) *ListNode {
	head := &ListNode{} //头节点
	node := head
	for _, item := range slice {
		node.Next = &ListNode{
			Val: item,
		}
		node = node.Next
	}
	return head.Next
}

方法二

通过指针,这题真正要考的应该是指针

func mergeTwoLists(list1 *ListNode, list2 *ListNode) *ListNode {
	head := &ListNode{}
	current := head
	for list1 != nil && list2 != nil {
		if list1.Val < list2.Val {
			current.Next = list1
			list1 = list1.Next
		} else {
			current.Next = list2
			list2 = list2.Next
		}
		current = current.Next
	}
	if list1 != nil {
		current.Next = list1
	} else if list2 != nil {
		current.Next = list2
	}
	//return current.Next
	//注意返回值!
	return head.Next
}
`