LeetCode 021. Merge Two Sorted Lists

来源:互联网 发布:网络系统面试 编辑:程序博客网 时间:2024/06/05 19:02

Merge Two Sorted Lists

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.

这道题最直观的方式是采用递归,每次处理一从两个链表中选择出一个值较小的节点,连接起来。

class Solution {public:    ListNode *mergeTwoLists(ListNode *l1, ListNode *l2)     {        if(!l1 && !l2)            return NULL;        else if(!l1)            return l2;        else if(!l2)            return l1;                    ListNode * head = NULL;        ListNode * temp;        if(l1->val >= l2->val)        {            head = l2;            head->next = mergeTwoLists(l1, l2->next);        }        else        {            head = l1;            head->next = mergeTwoLists(l1->next, l2);        }        return head;    }};

下面采用循环来解决这个问题

class Solution{public:    ListNode *mergeTwoLists(ListNode *l1, ListNode *l2)     {        if(!l1 && !l2)            return NULL;        else if(!l1)            return l2;        else if(!l2)            return l1;        ListNode * head = NULL;        ListNode * p1 = l1;ListNode * p2 = l2;        if(p1->val >= p2->val)        {            head = p2;p2 = p2->next;        }        else        {            head = p1;            p1 = p1->next;        }ListNode * p = head;while(p1 || p2){    if(!p1 || (p2 && p1->val >= p2->val )){p->next = p2;p2 = p2->next;}else{p->next = p1;p1 = p1->next;}p = p->next;}        return head;    }};


0 0
原创粉丝点击