day3
今天上午阅读刻意练习,困得亚批,下午写写博客。
21.Merge Two Sorted List
Merge two sorted linked lists and return it as a new sorted list. The new list should be made by splicing together the nodes of the first two lists.
Example:
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
分析
此处需要直接定义一个列表对象放与栈上,而不是new一个对象放在堆上。算法为:
A,B,C为三个指针光标,其中A,B为旧列表的指针,C为新定义的列表指针,依次扫描两个旧列表,旧列表当前指向元素较小者填入新列表,列表光标后移,直至两个旧列表遍历完毕,另外一个列表元素依次填入新列表,返回新列表即可。
算法用到递归思想
代码
java
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(null == l1) return l2;
if(null == l2) return l1;
if(l1.val <= l2.val) l1.next = mergeTwoLists(l1.next, l2);
else{
ListNode n = l1;
l1 = l2;
l1.next = mergeTwoLists(l1.next, n);
}
return l1;
}
}
c++
#include<iostream>
using namespace std;
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
struct ListNode
{
int val;
ListNode *next;
ListNode() :val(0), next(nullptr) {}
ListNode(int x) :val(x), next(nullptr) {}
ListNode(int x,ListNode *next):val(x),next(next){}
};
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if (nullptr == l1)
return l2;
if (nullptr == l2)
return l1;
if (l1->val <= l2->val) {
l1->next = mergeTwoLists(l1->next, l2);
}
else {
ListNode *root = new ListNode();
root = l1;
l1 = l2;
l1->next = mergeTwoLists(l1->next, root);
}
return l1;
}
void printList(ListNode *root) {
while (root) {
cout << root->val << endl;
root = root->next;
}
}
};
int main() {
Solution solution;
ListNode *l1 = new ListNode(1, new ListNode(2, new ListNode(4)));
cout << "---l1---" << endl;
solution.printList(l1);
ListNode *l2 = new ListNode(1, new ListNode(3, new ListNode(4)));
cout << "---l2---" << endl;
solution.printList(l2);
l1 = solution.mergeTwoLists(l1, l2);
cout << "---l1与l2合并后---" << endl;
solution.printList(l1);
return 0;
}
时间复杂度和空间复杂度分析
时间复杂度 | 空间复杂度 |
---|---|
O(n) | O(1) |