1. 程式人生 > >LeetCode21. Merge Two Sorted Lists(C++)

LeetCode21. Merge Two Sorted Lists(C++)

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.

Example:

Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4

解題思路:雙指標法;

/**
 * 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) {
        ListNode* head,*temp,*p,*q;
        head=new ListNode(0);
        temp=head;
        p=l1;q=l2;
        while(p!=NULL&&q!=NULL){
            if(p->val<=q->val){
                temp->next=p;
                temp=temp->next;
                p=p->next;
            }
            else{
                temp->next=q;
                temp=temp->next;
                q=q->next;
            }
        }
        if(p!=NULL)
            temp->next=p;
        if(q!=NULL)
            temp->next=q;
        return head->next;
    }
};