剑指Offer-第2天 链表(简单)
第一题
题目链接: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;
}
};
结果(个人)
结果(官方)