Problem: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.
Solution:two ordered lists, each taking the smallest element of the head, and then remove the element from the original linked list, loop in turn
Main topic:given two ordered linked lists, the linked list is required to be merged into an ordered list, and no additional space can be used
Java source Code (344MS):
/** * Definition for singly-linked list. * public class ListNode {* int val; * ListNode Next; * listnode (int x) {val = x;}}} */public class Soluti On {public listnode mergetwolists (listnode L1, ListNode L2) { ListNode head,p; if (l1==null) return L2; if (l2==null) return L1; if (L1.val > L2.val) { p=l2;l2=l2.next; } else{ p=l1;l1=l1.next; } head=p; while (L1!=null && l2!=null) { if (L1.val > L2.val) { p.next=l2;l2=l2.next; } else{ p.next=l1;l1=l1.next; } P=p.next; } if (l1==null) p.next=l2; else P.NEXT=L1; return head; }}
C Language Source code (3MS):
/** * Definition for singly-linked list. * struct ListNode {* int val; * struct ListNode *next; *}; */struct listnode* mergetwolists (struct listnode* L1, struct listnode* L2) { struct listnode *head,*p; if (l1==null) return L2; if (l2==null) return L1; if (L1->val > L2->val) { p=l2; l2=l2->next; } else{ p=l1; l1=l1->next; } head=p; while (L1!=null && l2!=null) { if (L1->val > L2->val) { p->next=l2; l2=l2->next; } else{ p->next=l1; l1=l1->next; } p=p->next; } if (l1==null) p->next=l2; else p->next=l1; return head;}
C + + source code (13MS):
/** * Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * listnode (int x): Val (x), Next (NULL) {} *}; */class Soluti On {public: listnode* mergetwolists (listnode* L1, listnode* L2) { ListNode *head,*p; if (l1==null) return L2; if (l2==null) return L1; if (L1->val > L2->val) { p=l2;l2=l2->next; } else{ p=l1;l1=l1->next; } head=p; while (L1!=null && l2!=null) { if (L1->val > L2->val) { p->next=l2;l2=l2->next; } else{ p->next=l1;l1=l1->next; } p=p->next; } if (l1==null) p->next=l2; else p->next=l1; return head; };
python source code (67MS):
# Definition for singly-linked list.# class listnode:# def __init__ (self, x): # self.val = x# Self.next = Nonec Lass Solution: # @param {listnode} L1 # @param {ListNode} L2 # @return {listnode} def mergetwolists (self , L1, L2): if L1==none:return L2 if l2==none:return L1 p=l1 if L1.val > l2.val: p=l2;l2= L2.next else:p=l1;l1=l1.next head=p while L1!=none and L2!=none: if L1.val > L2.val: P.next=l2;l2=l2.next else:p.next=l1;l1=l1.next p=p.next if L1==none:p.next=l2 else:p.next= L1 return head
Leetcode Merge Sorted Lists (C,c++,java,python)