title :
Merge sorted linked lists and return it as a new list. The new list should is made by splicing together the nodes of the first of the lists.
code : OJ online test via runtime:208 ms
1 #Definition for singly-linked list.2 #class ListNode:3 #def __init__ (self, x):4 #self.val = x5 #Self.next = None6 7 classSolution:8 #@param listnodes9 #@return a ListNodeTen defmergetwolists (self, L1, L2): One ifL1 isNone: A returnL2 - ifL2 isNone: - returnL1 the -Dummyhead =listnode (0) -Dummyhead.next =None -p =Dummyhead + whileL1 is notNone andL2 is notNone: - ifL1.val >L2.val: +P.next =L2 AL2 =L2.next at Else: -P.next =L1 -L1 =L1.next -p =P.next - ifL1 is notNone: -P.next =L1 in Else: -P.next =L2 to returnDummyhead.next
Ideas :
Virtual table Head Dummyhead set up do not move, set a P=hummyhead, and then start from the processing P.next, and finally return to Hummyhead to get the correct results
The two-table pointer moves one step at a pace and determines which insert p.next by comparing the size of the Val
Notice that each time you execute the judgment, move the pointer p=p.next
Leetcode "Merge Sorted Lists" Python implementation