@@ -23,12 +23,17 @@ class Solution {
2323 srand (time (NULL ));
2424 }
2525 ListNode *mergeTwoLists (ListNode *l1, ListNode *l2) {
26- if (random ()%2 ){
27- return mergeTwoLists01 (l1, l2);
26+ switch (random ()%2 ){
27+ case 0 :
28+ return mergeTwoLists01 (l1, l2);
29+ case 1 :
30+ return mergeTwoLists02 (l1, l2);
31+ default :
32+ return mergeTwoLists03 (l1, l2);
2833 }
29- return mergeTwoLists02 (l1, l2);
3034 }
3135
36+ /* merge the 2nd list into 1st list*/
3237 ListNode *mergeTwoLists01 (ListNode* head1, ListNode* head2){
3338 ListNode *p1 = head1, *p2=head2;
3439 static ListNode dummy (0 );
@@ -55,6 +60,7 @@ class Solution {
5560 }
5661
5762
63+ /* merge two lists to the new list */
5864 ListNode *mergeTwoLists02 (ListNode *l1, ListNode *l2) {
5965 ListNode *l=NULL , *p=NULL ;
6066
@@ -82,7 +88,7 @@ class Solution {
8288
8389 return l;
8490 }
85- private:
91+
8692 ListNode* mergeTheRest (ListNode* l, ListNode*head, ListNode* tail){
8793 if (l){
8894 if (head && tail ){
@@ -93,4 +99,28 @@ class Solution {
9399 }
94100 return head;
95101 }
102+
103+ /*
104+ * You can see the 2nd slution's code is quite complicated,
105+ * because it need to check the (head==NULL) situation.
106+ * We can use the "pointer to pointer" to make the code more clean
107+ * however, this would be bad for performance.
108+ */
109+ ListNode *mergeTwoLists03 (ListNode *l1, ListNode *l2) {
110+ ListNode *head = NULL ;
111+ ListNode **pTail = &head;
112+ while (l1 != NULL && l2 != NULL ) {
113+ if (l1->val < l2->val ) {
114+ *pTail = l1;
115+ l1 = l1->next ;
116+ } else {
117+ *pTail = l2;
118+ l2 = l2->next ;
119+ }
120+ pTail = &(*pTail)->next ;
121+ }
122+ *pTail = (l1 != NULL ? l1 : l2);
123+ return head;
124+ }
125+
96126};
0 commit comments