算法第五周Merge Two Sorted Lists[easy]

来源:互联网 发布:linux解压tar.xz文件 编辑:程序博客网 时间:2024/05/24 16:15

Merge Two Sorted Lists[easy]


Description

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.


Solution

这道题目是将两个已经排序的链表排序得到新的链表。
我们只需遍历两个链表不断地将值小的结点链接到新链表上即可。
特别要注意指针为空的情况。

class Solution {public:    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {        ListNode* head = new ListNode(INT_MIN);        ListNode* t = head;        while (l1 && l2) {            if (l1->val < l2->val) {                t->next = l1;                t = t->next;                l1 = l1->next;            } else {                 t->next = l2;                 t = t->next;                 l2 = l2->next;            }        }        if (l1 == NULL&&l2 != NULL) {            t->next = l2;        }        if (l1 != NULL&&l2 == NULL) {            t->next = l1;        }        return head->next;    }};
原创粉丝点击