【算法训练】

算法新手练习

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档


前言

`提示:练习算法数据结构记录


一、Merge two sorted linked lists and return it as a new list(合并两个有序链表)?

ListNode* mergeTwoSortedList(ListNode *l1,ListNode *l2)
{
    ListNode* dummy = new ListNode(0);
    ListNode* cur = dummy;

    while(l1 && l2)
    {
        if(l1->value <= l2->value)
        {
            cur->next = l1;
            l1 = l1->next;
        }
        else{
            cur->next = l2;
            l2 = l2->next;
        }
        cur = cur->next;
    }

    cur->next = (l1 != nullptr) ? l1 : l2;
    return dummy->next;
}

二、先序遍历二叉树?

vector<int> preorderTraversal(TreeNode* root)
{
    vector<int> result;
    if(root == NULL) return result;
    stack<TreeNode*> s;
    s.push(root);
    while(!s.empty())
    {
        TreeNode *node = s.top();
        s.pop();
        result.push_back(node->val);
        if(node->right) {
            s.push(node->right);
        }
            

        if(node->left){
            s.push(node->right);
        }
    }
    return result;
}

二,单链表复制(包含randnode)

如果无空间复杂度限制,可以使用hashmap
空间复杂度O(1)算法如下

ListNode* copyListWithRomd(ListNode* head)
{
	if (!head)
	{
		return nullptr;
	}

	ListNode* cur = head;
	ListNode* next = nullptr;

	while (cur)
	{
		next = cur->next;
		cur->next = new ListNode(cur->value);
		cur->next->next = next;
		cur = next;
	}

	ListNode* curCopy = nullptr;
	cur = head;
	while (cur)
	{
		next = cur->next->next;
		curCopy = cur->next;
		curCopy->rand = cur->rand ? cur->rand->next : nullptr;
		cur = next;
	}

	ListNode* res = head->next;
	cur = head;
	while (cur)
	{
		next = cur->next->next;
		curCopy = cur->next;
		cur->next = next;
		curCopy->next = next ? next->next : nullptr;
		cur = next;
	}
	return res;
}

总结

使用dummyNode处理有序链表合并

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值