021 Merge Two Sorted Lists
2016-04-05 23:03
375 查看
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.
Subscribe to see which companies asked this question
#include <iostream>
#include <string>
#include <map>
#include <algorithm>
using namespace std;
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode* head = NULL;
ListNode* l1pre = NULL;
if(l1==NULL) return l2;
else if (l2 == NULL) return l1;
else if(l2==NULL && l1==NULL) return NULL;
if(l1->val > l2->val) {
head = l2;
l2 = l1;
l1 = head;
}
head = l1;
for(; l1 != NULL && l2 != NULL;) {
if(l1->val <= l2->val) {
l1pre = l1;
l1 = l1->next;
} else {
ListNode *l2next = l2->next;
l2->next = l1;
if(l1pre!=NULL)
l1pre->next = l2;
l1pre = l2;
l2=l2next;
}
}
if(l1==NULL) {
l1pre->next = l2;
}
return head;
}
};
Subscribe to see which companies asked this question
#include <iostream>
#include <string>
#include <map>
#include <algorithm>
using namespace std;
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode* head = NULL;
ListNode* l1pre = NULL;
if(l1==NULL) return l2;
else if (l2 == NULL) return l1;
else if(l2==NULL && l1==NULL) return NULL;
if(l1->val > l2->val) {
head = l2;
l2 = l1;
l1 = head;
}
head = l1;
for(; l1 != NULL && l2 != NULL;) {
if(l1->val <= l2->val) {
l1pre = l1;
l1 = l1->next;
} else {
ListNode *l2next = l2->next;
l2->next = l1;
if(l1pre!=NULL)
l1pre->next = l2;
l1pre = l2;
l2=l2next;
}
}
if(l1==NULL) {
l1pre->next = l2;
}
return head;
}
};
相关文章推荐
- 4.单行函数-日期函数
- MediaRecorder类介绍
- nginx
- 陈皓:一个 fork 的面试题
- 刷题_day1_vv
- mono+jexus 之连接数据库
- 《NumPy Beginner's Guide》笔记Chapter9
- mysql的约束
- 《NumPy Beginner's Guide》笔记Chapter8
- 华为OJ题目(二十):合法IP
- 通过 PCIE Inbound
- UVa 10902 Pick-up Sticks
- 《linux内核设计与实现》读书笔记——第三章
- 结对编程(黄金分割点)
- 《NumPy Beginner's Guide》笔记Chapter7
- 分离编译
- 深入掌握JMS(七):DeliveryMode例子
- 把字符串中空格替换为"%20"
- 《NumPy Beginner's Guide》笔记Chapter6
- 关于CPU负载和CPU利用率