首页 > 其他 > 详细

【LeetCode】32.Linked List — Merge Two Sorted Lists合并两个有序链表

时间:2019-09-05 09:57:27      阅读:62      评论:0      收藏:0      [点我收藏+]

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;
    }
};

 

【LeetCode】32.Linked List — Merge Two Sorted Lists合并两个有序链表

原文:https://www.cnblogs.com/hu-19941213/p/11462897.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!