21-Merge Two Sorted Lists

来源:互联网 发布:阿里云消息推送 编辑:程序博客网 时间:2024/06/11 06:24

难度:easy
类别:linked list

1.题目描述

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.
注:不仅是合并,同时要保持合并后有序。

2.算法分析

(1)首先需要判断两个链表是否为空并进行处理。
(2)对head结点先进行处理,并且将head结点存在result中.
(3)对当前的list1和list2的结点进行值得比较,将小的加进结果链表中。
(4)结果链表后移。

3.代码实现

class Solution {public:    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {        if (l1 == NULL) return l2;        if (l2 == NULL) return l1;        ListNode* head = NULL;        if (l1->val >= l2->val) {            head = new ListNode(l2->val);            l2 = l2->next;        }        else {            head = new ListNode(l1->val);            l1 = l1->next;        }        ListNode* result = head;        while (l1 != NULL || l2 != NULL) {            if (l1 == NULL) {                head->next = new ListNode(l2->val);                l2 = l2->next;            } else if (l2 == NULL) {                head->next = new ListNode(l1->val);                l1 = l1->next;            } else {                if (l1->val >= l2->val) {                    head->next = new ListNode(l2->val);                    l2 = l2->next;                } else {                    head->next = new ListNode(l1->val);                    l1 = l1->next;                }            }            //  要特别注意往后移动,head = head->next;            head = head->next;        }        head->next = NULL;        return result;    }};