首页 > 其他 > 详细

leetcode 21. 合并两个有序链表(Merge Two Sorted Lists)

时间:2019-03-18 16:05:07      阅读:126      评论:0      收藏:0      [点我收藏+]

题目描述:

将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。

示例:


    输入:1->2->4, 1->3->4
    输出: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 = NULL;
        if(l1 == NULL){
            head = l2;
        }else if(l2 == NULL){
            head = l1;
        }else{
            ListNode* cur = NULL;
            ListNode* h1 = l1, *h2 = l2;
            while(h1 != NULL && h2 != NULL){
                if(h1->val < h2->val){
                    if(head == NULL){
                        head = new ListNode(h1->val);
                        cur = head;
                    }else{
                        cur->next = new ListNode(h1->val);
                        cur = cur->next;
                    }
                    h1 = h1->next;
                }else{
                    if(head == NULL){
                        head = new ListNode(h2->val);
                        cur = head;
                    }else{
                        cur->next = new ListNode(h2->val);
                        cur = cur->next;
                    }
                    h2 = h2->next;
                }
            }
            while(h1 != NULL){
                cur->next = new ListNode(h1->val);
                h1 = h1->next;
                cur = cur->next;
            }
            while(h2 != NULL){
                cur->next = new ListNode(h2->val);
                h2 = h2->next;
                cur = cur->next;
            }
        }
        return head;
    }
};

leetcode 21. 合并两个有序链表(Merge Two Sorted Lists)

原文:https://www.cnblogs.com/zhanzq/p/10552577.html

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