merge_two_sorted_lists

  • 2022-12-14
  • 浏览 (568)

merge_two_sorted_lists.go 源码

package main

//合并两个有序的链表

//迭代法
func mergeTwoLists1(l1 *ListNode, l2 *ListNode) *ListNode {
	node := ListNode{-1, nil}
	p := &node
	for l1 != nil && l2 != nil {
		if l1.Val < l2.Val {
			p.Next = l1
			l1 = l1.Next
		} else {
			p.Next = l2
			l2 = l2.Next
		}
		p = p.Next
	}

	if l1 != nil {
		p.Next = l1
	} else {
		p.Next = l2
	}
	return node.Next
}

//递归
func mergeTwoLists2(l1 *ListNode, l2 *ListNode) *ListNode {
	if l1 == nil {
		return l2
	} else if l2 == nil {
		return l1
	} else if l1.Val < l2.Val {
		l1.Next = mergeTwoLists2(l1.Next, l2)
		return l1
	} else {
		l2.Next = mergeTwoLists2(l1, l2.Next)
		return l2
	}
}

你可能感兴趣的文章

add_two_numbers

add_two_numbers_ii

intersection_linked_lists

0  赞