题目描述
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
样例输入
1 3 5 7 9
2 4
样例输出
1 2 3 4 5 7 9
package main
import "fmt"
type ListNode struct {
Val int
Next *ListNode
}
func print(head *ListNode) {
for head != nil {
fmt.printf("%d - >", head.Val)
head = head.Next
}
}
func MergeTwoList(l1 *ListNode, l2 *ListNode) *ListNode {
res := &ListNode{}
cur := res
for l1 != nil || l2 != nil {
if l1 == nil {
cur.Next = l2
break
} else if l2 == nil {
cur.Next = l1
break
}
if l1.Val > l2.Val {
cur.Next = l2
cur = cur.Next
l2 = l2.Next
} else {
cur.Next = l1
cur = cur.Next
l1 = l1.Next
}
}
return res.Next
}
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def merge_two_list(self, pHead1, pHead2):
if pHead1 == None:
return pHead2
elif pHead2 == None:
return pHead1
pMerage = None
if pHead1.val < pHead2.val:
pMerage = pHead1
pMerage.next = self.merge_two_list(pHead1.next, pHead2)
else:
pMerage = pHead2
pMerage.next = self.merge_two_list(pHead1, pHead2.next)
return pMerage
网友评论