首页 > 代码库 > LeetCode--Merge Two Sorted Lists

LeetCode--Merge Two Sorted Lists

重新写了下,代码看着清爽多了

 1 /** 2  * Definition for singly-linked list. 3  * struct ListNode { 4  *     int val; 5  *     ListNode *next; 6  *     ListNode(int x) : val(x), next(NULL) {} 7  * }; 8  */ 9 class Solution {10 public:11     ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {12         ListNode tmp(-1);13         ListNode *resHead = &tmp;14         ListNode *resHead_output = resHead;15         while(l1 != NULL && l2 != NULL){16             if(l1->val < l2->val){17                 resHead->next = l1;18                 l1 = l1->next;19             }20             else{21                 resHead->next = l2;22                 l2 = l2->next;23             }24             resHead = resHead->next;25         }26         if(l1){27             resHead->next = l1;28         }29         if(l2){30             resHead->next = l2;31         }32         return resHead_output->next;33     }34 };

 

LeetCode--Merge Two Sorted Lists