LeetCode:21. Merge Two Sorted Lists
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
Example:
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
合并两个有序链表
思路
同时遍历两个链表,val值小的插入到新的链表,知道有个链表遍历结束,再把剩余的那个链表合并到新链表。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
head1,head2 = l1,l2
newl = ListNode(0)
newhead = newl
while (head1 is not None and head2 is not None):
if head1.val <= head2.val:
tmp = ListNode(head1.val)
newhead.next = tmp
newhead = newhead.next
head1 = head1.next
elif head2.val <= head1.val:
tmp = ListNode(head2.val)
newhead.next = tmp
newhead = newhead.next
head2 = head2.next
if head1 is not None:
newhead.next = head1
if head2 is not None:
newhead.next = head2
return newl.next
THE END.