[面试真题] LeetCode:Merge Two Sorted Lists

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two 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         // Start typing your C/C++ solution below
13         // DO NOT write int main() function
14         ListNode *head = new ListNode(0);
15         ListNode *tail = head;
16         ListNode *a = l1;
17         ListNode *b = l2;
18         while(a || b){
19             if(a && b && a->val < b->val){
20                 tail->next = a;
21                 a = a->next;
22             }else if (a && b && a->val > b->val){
23                 tail->next = b;
24                 b = b->next;
25             }else if(a){
26                 tail->next = a;
27                 a = a->next;
28             }else{
29                 tail->next = b;
30                 b = b->next;
31             }
32             tail = tail->next;
33         }
34         return head->next;
35     }
36 };

Run Status: Accepted!
Program Runtime: 56 milli secs

Progress: 208/208 test cases passed.
posted @ 2013-05-12 21:36  infinityu  阅读(194)  评论(0编辑  收藏  举报