剑指offer专项计划--第二天

剑指 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;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值