剑指 Offer 06. 从尾到头打印链表
思考:先把链表转为数组,再用reverse()倒置
class Solution {
public:
vector<int> reversePrint(ListNode* head) {
vector<int> vec;
ListNode* L1=head;
while(L1){
vec.push_back(L1->val);
L1=L1->next;
}
reverse(vec.begin(), vec.end());
return vec;
}
};
剑指 Offer 24. 反转链表
思考:顺序读取,头插法插入
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head){
ListNode* L2=head;
ListNode* L1=new ListNode(L2->val);
L2=L2->next;
while(L2){
ListNode* L3=new ListNode(L2->val);
L3->next=L1;
L1=L3;
L2=L2->next;
}
return L1;
}
else{
return NULL;
}
}
};
剑指 Offer 35. 复杂链表的复制
看了帅弟的视频里的思路之后,自己按着思路敲出来了,第一次完全上手解决了还是超级开心的。其中踩了两个坑,报了错,整理记录一下。
Random pointer of node with label 13 points to a node from the original list
某一个复制后的节点的random指向了原节点
runtime error: member access within null pointer of type ‘Node‘ (solution.cpp)
直接把不存在的指针赋值给当前指针
class Solution {
public:
Node* copyRandomList(Node* head) {
if(head){
Node* L1=head;
Node* L2=new Node(L1->val);
L2->next=L1->next;
L1->next=L2;
L1=L2->next;
while(L1){
Node* L2=new Node(L1->val);
L2->next=L1->next;
L1->next=L2;
L1=L2->next;
}
L1=head;
L2=head->next;
while(L1){
if(L1->random!=NULL) L2->random=L1->random->next;//没有判断指针为空的情况就赋值,也是第一个错误出现的地方,一定要指向复制的节点
else L2->random=NULL;
L1=L2->next;
if(L1) L2=L1->next;//没有判断指针为空的情况就赋值
else L2=NULL;
}
L1=head;
L2=head->next;
Node* temp=L2;
Node* L3;
while(L2->next){
L1->next=L2->next;
L1=L2->next;
if(L2->next){
L3=L2->next->next;
L2->next=L3;
L2=L3;
}
}
L1->next=NULL;
return temp;
}
else return NULL;
}
};