算法新手练习
提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
文章目录
前言
`提示:练习算法数据结构记录
一、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处理有序链表合并