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.
Merges two ordered linked lists sequentially.
Mainly the operation of the list, linked to the list of questions to take C + + to do.
Idea: Compare the Val value of the current element of the two linked list in turn, p points to the small one, and the small pointer moves back. Note that if the list is empty, the pointer moves back to a null-out loop, and if the following determines which is not empty then P points to its string.
C++:
/** * Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * ListNode (int x ): Val (x), Next (NULL) {}}; */ class solution {public:listnode* mergetwolists (listnode* L1, listnode* L2) {listnode* p=NewListNode (0); listnode* q=p;//q Save Linked list header while(L1 && L2) {if(l1->Val>= l2->Val) {p->next=l2; l2=l2->next; }Else{p->next=l1; l1=l1->next; } p=p->next;//Note that the P pointer also moves back}if(L1) p->next=l1;if(L2) p->next=l2;returnq->next;//Start from the second node, discard the beginning of the 0}};
10ms AC.
Put on a python:
class solution(object): "' Test instructions: Merging two ordered linked lists ' def mergetwolists(self, L1, L2):dummy = ListNode (0) TMP = Dummy whileL1! =None andL2! =None:ifL1.val < L2.val:tmp.next = L1 L1 = L1.nextElse: Tmp.next = L2 L2 = l2.next tmp = Tmp.nextifL1! =None: Tmp.next = L1Else: Tmp.next = L2returnDummy.next
Similar.
Leetcode-21-merge Sorted Lists