@@ -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
@@ -83,6 +89,23 @@ class Solution {
8389 return l;
8490 }
8591
92+ ListNode* mergeTheRest (ListNode* l, ListNode*head, ListNode* tail){
93+ if (l){
94+ if (head && tail ){
95+ tail->next = l;
96+ }else {
97+ head = l;
98+ }
99+ }
100+ return head;
101+ }
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+ */
86109 ListNode *mergeTwoLists03 (ListNode *l1, ListNode *l2) {
87110 ListNode *head = NULL ;
88111 ListNode **pTail = &head;
@@ -100,15 +123,4 @@ class Solution {
100123 return head;
101124 }
102125
103- private:
104- ListNode* mergeTheRest (ListNode* l, ListNode*head, ListNode* tail){
105- if (l){
106- if (head && tail ){
107- tail->next = l;
108- }else {
109- head = l;
110- }
111- }
112- return head;
113- }
114126};
0 commit comments