您的位置:首页 > 其它

021 Merge Two Sorted Lists [Leetcode]

2015-10-27 16:53 357 查看
题目内容:

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.

解题思路:

很基础的问题,注意处理长度不等的问题,同样使用附加头结点化简处理。

非递归实现代码如下,运行时间8ms:

/**
* 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 == NULL)
return l2;
if (l2 == NULL)
return l1;

ListNode *p1(l1), *p2(l2), *pre_head(new ListNode(0)), *cur(pre_head);

while (p1 != NULL && p2 != NULL) {
if (p1->val < p2->val) {
cur->next = p1;
p1 = p1->next;
}
else {
cur->next = p2;
p2 = p2->next;
}
cur = cur->next;
}
if (p1 != NULL) {
cur->next = p1;
}
else if (p2 != NULL) {
cur->next = p2;
}

ListNode *head = pre_head->next;
pre_head->next = NULL;
delete pre_head;
return head;
}
};


递归实现:

/**
* 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 == NULL)
return l2;
if(l2 == NULL)
return l1;

if(l1->val < l2->val) {
l1->next = mergeTwoLists(l1->next, l2);
return l1;
}
else {
l2->next = mergeTwoLists(l1, l2->next);
return l2;
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: