第一题
题目链接:https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof/
个人题解:开一个数组,从头到尾遍历,然后反转数组即可
代码:
class Solution {
public:
vector<int> reversePrint(ListNode* head) {
vector<int> res;
while(head){
res.push_back(head->val);
head=head->next;
}
reverse(res.begin(),res.end());
return res;
}
};
结果:
第二题
题目链接:https://leetcode-cn.com/problems/fan-zhuan-lian-biao-lcof/
个人题解:开一个 \(cur\) 和 \(head\) 一样,然后一步一步迭代即可
代码:
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode *prev = nullptr;
ListNode *cur = head;
while (cur)
{
ListNode *next = cur->next;
cur->next = prev;
prev = cur, cur = next;
}
return prev;
}
};
结果:
第三题
题目链接:https://leetcode-cn.com/problems/fu-za-lian-biao-de-fu-zhi-lcof/
个人题解:开一个哈希表(慢)。标答不是很能理解
个人代码 和 官方题解
class Solution {
public:
unordered_map<Node*,Node*> hash;
Node* copyRandomList(Node* head) {
if(head==nullptr) return nullptr;
if(!hash.count(head)){
auto Now=new Node(head->val);
hash[head]=Now;
Now->next=copyRandomList(head->next);
Now->random=copyRandomList(head->random);
}
return hash[head];
}
};
class Solution {
public:
Node* copyRandomList(Node* head) {
if (head == nullptr) {
return nullptr;
}
for (Node* node = head; node != nullptr; node = node->next->next) {
Node* nodeNew = new Node(node->val);
nodeNew->next = node->next;
node->next = nodeNew;
}
for (Node* node = head; node != nullptr; node = node->next->next) {
Node* nodeNew = node->next;
nodeNew->random = (node->random != nullptr) ? node->random->next : nullptr;
}
Node* headNew = head->next;
for (Node* node = head; node != nullptr; node = node->next) {
Node* nodeNew = node->next;
node->next = node->next->next;
nodeNew->next = (nodeNew->next != nullptr) ? nodeNew->next->next : nullptr;
}
return headNew;
}
};
结果(个人)
结果(官方)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。