LeetCode菜鸟进化史day3

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)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值