[Leetcode] Merge Two Sorted Lists

来源:互联网 发布:华为网络机顶盒怎么样 编辑:程序博客网 时间:2024/05/17 22:59

描述

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.

将两个有序链表合并。

分析1

这道题可以使用递归的方法来完成,当两个链表都非空时,将两个表头中值较小的一个加入答案,同时该表头向后移动一位,当两个链表有一个空时,将另外一个链表加入答案。

代码1

/** * 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) {        if (!l1) return l2;        if (!l2) return l1;        if (l1->val <= l2->val) {            l1->next = mergeTwoLists(l1->next, l2);            return l1;        } else {            l2->next = mergeTwoLists(l1, l2->next);            return l2;        }    }};

分析2

根据递归的代码可以很容易改为非递归的,代码如下。

代码2

/** * 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 *dummy = new ListNode(-1), *p = dummy;        while (l1 && l2) {            if (l1->val <= l2->val) {                p->next = l1; l1 = l1->next; p = p->next;            } else {                p->next = l2; l2 = l2->next; p = p->next;            }        }        if (l1) p->next = l1;        else p->next = l2;        return dummy->next;    }};
0 0