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.
Title Requirements:
Merge two ordered linked lists
Attention:
Can't open up new node space.
Problem Solving Ideas:
1, merge sort, create a new head node, the beginning and end of the two linked list, and then compare its size, each time the head pointer pointed to the small one.
2. Recursive thinking
Code:
/** Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * ListNode (int x) : Val (x), Next (NULL) {}}; *///Merge Combination MethodclassSolution { Public: ListNode*mergetwolists (ListNode *l1, ListNode *L2) {ListNode Head (0); ListNode*lst; LST=&Head; while(L1 &&L2) { if(l1->val<=l2->val) {LST->next=L1; L1=l1->Next; } Else{LST->next=L2; L2=l2->Next; } LST=lst->Next; } if(L1) LST->next=L1; if(L2) LST->next=L2; returnHead.next; }};//Recursive MethodclassSolution { Public: ListNode*mergetwolists (ListNode *l1, ListNode *L2) { if(L1 = = NULL)returnL2; if(L2 = = NULL)returnL1; if(L1->val < l2->val) {L1->next = Mergetwolists (l1->Next, L2); returnL1; } Else{L2->next = Mergetwolists (l2->Next, L1); returnL2; } }
(leetcode) Merge Sorted Lists