The merge of Leetcode problem solving and the original problem of Sorted lists
The two ordered linked lists are stitched together into an ordered list.
Note the point:
- No additional application nodes are required, mainly linking the nodes in the original list
- One of the original linked list is already all in the new linked list, the rest of the list can be directly spliced
Example:
Input: L1 = 1->2->4, L2 = 3
Output: 1->2->3->4
Thinking of solving problems
To avoid classification discussions, add a dummy head node. Now only two pointers are required to point to the original two linked lists, and the smaller nodes are added to the new linked list. The parameters passed in L1 and L2 can be used as pointers to traverse two linked lists.
AC Source
# Definition for singly-linked list. class listnode(object): def __init__(self, x):Self.val = x Self.next =None class solution(object): def mergetwolists(self, L1, L2): "" : Type L1:ListNode:type l2:ListNode:rtype:ListNode "" "temp = ListNode (-1) Head = Temp whileL1 andL2:ifL1.val > l2.val:temp.next = L2 L2 = L2.nextElse: temp.next = L1 L1 = L1.next temp = Temp.nextifL1:temp.next = L1Else: Temp.next = L2returnHead.nextif__name__ = ="__main__":assertSolution (). Mergetwolists (ListNode (1), ListNode (2). val = =1
Welcome to my GitHub to get the relevant source code.
Leetcode Merge Sorted Lists