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

题目描述:

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

示例:


    输入: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;
    }
};
posted @ 2019-03-18 15:49  zhanzq1  阅读(97)  评论(0)    收藏  举报