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.

  

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *mergeTwoLists(ListNode *list1, ListNode *list2) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if(list1 == NULL && list2 == NULL) return NULL;
    	
		ListNode *head = NULL,  *cur = NULL;
		while(list1 && list2){	
			ListNode *tp;
			if(list1->val >list2->val){
				tp = list2;
				list2 = list2->next;
			}else{
				tp = list1;
				list1 = list1->next;
			}
			
			if(cur == NULL){
				head = cur = tp;
			}else{
				cur->next = tp;
				cur = tp;
			}
		}
		
		list1 = list1 == NULL ? list2 : list1;
		if(cur == NULL) 
				return list1;
		  else
				cur->next = list1;
		
		return head;	
    }
};

  重写后: 定义一个伪头,省去所有的边界问题。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if(l1 == NULL) return l2;
        if(l2 == NULL) return l1;
        ListNode * head = new ListNode(1);
        ListNode * p = head;
        while(l1 != NULL && l2 != NULL){
        
            if(l1->val < l2->val){
                p->next = l1;
                p = l1;
                l1 = l1->next;
            }else{
                p->next = l2;
                p = l2;
                l2 = l2->next;
            }
        }
        
        p->next = l1 == NULL ? l2 : l1;
        p = head->next;
        delete head;
        
        return p;    
    }
};

 

posted @ 2013-04-24 11:58  冰点猎手  阅读(142)  评论(0编辑  收藏  举报