Merge Two Sorted Lists

Definition for singly-linked list.

/**
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/

 

Method 1: (Double-Pointer)

class Solution {
public:
    ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
        ListNode *p1 = NULL;
        ListNode **p2 = &p1; // declare a double pointer
        while(l1&&l2){
            if(l1->val<=l2->val){
                *p2 = l1; // For first loop, p1 stores the entry of Linked List
                l1 = l1->next;
            }else{
                *p2 = l2; // For first loop, p1 stores the entry of Linked List
                l2 = l2->next;
            }
            p2 = &((*p2)->next); // After first loop, p2 stores the address of the Linked List
        }
        if(l1) 
            *p2=l1;
        else 
            *p2=l2;
        return p1;
    }
};

 

 

 

posted @ 2013-10-19 07:29  WinsCoder  阅读(119)  评论(0编辑  收藏  举报