【LeetCode】32.Linked List — 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.

Example:

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

因为没有空间要求,所以想到ListNode*head = new ListNode(INT_MIN);重新定义一个链表,分别比较两个有序链表的大小然后将所在结点一次加入到定义的新链表中。

最后注意释放头结点空间。

/**
 * 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*p1=l1;
        ListNode*p2=l2;
        if(p1==NULL) return p2;
        if(p2==NULL) return p1;
        ListNode*head = new ListNode(INT_MIN);
        ListNode*tag=head;
        while(p1!=NULL&&p2!=NULL)
        {
            if(p1->val>=p2->val)
            {
                ListNode*D=p2;
                p2=p2->next;
                D->next=NULL;
                tag->next=D;
                tag=tag->next;
            }
            else{
                ListNode*D=p1;
                p1=p1->next;
                D->next=NULL;
                tag->next=D;
                tag=tag->next;
            }
        }
        if(p1!=NULL)
        {
            tag->next=p1;
            ListNode*H=head;
            head=head->next;
            delete H;
        }
        if(p2!=NULL)
        {
            tag->next=p2;
            ListNode*H=head;
            head=head->next;
            delete H;
        }
        return head;
    }
};

 

posted @ 2019-09-05 09:03  蓝天下的一棵草  阅读(230)  评论(0编辑  收藏  举报