代码随想录训练营第三天|203.移除链表元素,707.设计链表,206.反转链表

203. 移除链表元素 - 力扣(Leetcode)

 设置虚拟头节点是为了删除头节点时更加方便

注:不清除指针也能过,但为了防止出错,还是清除的好

class Solution {
public:
    ListNode* removeElements(ListNode* head, int val) {
        ListNode *dummy=new ListNode(0);
        dummy->next=head;
        ListNode *cur=dummy;
        while(cur->next!=nullptr)
        {
            if(cur->next->val==val)
            {
                //ListNode *tmp=cur->next;
                cur->next=cur->next->next;
                //delete tmp;

            }
            else
            cur=cur->next;
        }
        //head=dummy->next;
        //delete dummy;
        //return head;
        return dummy->next;
    }
};

707. 设计链表 - 力扣(Leetcode) 

 初版:细节内容没有考究,只是能过,后面得再看看

class MyLinkedList {
public:
    struct LinkedNode {
        int val;
        LinkedNode* next;
        LinkedNode(int val):val(val), next(nullptr){}
    };
    MyLinkedList() {
       dummy=new ListNode(0);
       size=0; 
    }
    
    int get(int index) {
        if(index<0||index>size-1)
        return -1;
        else
        {
            ListNode *cur=dummy->next;
            while(index--)
            {
                cur=cur->next;
            }
            return cur->val;
        }
    }
    
    void addAtHead(int val) {
        ListNode *cur=dummy;
        ListNode *tmp=new ListNode(val);
        tmp->next=cur->next;
        cur->next=tmp;
        size++;
    }
    
    void addAtTail(int val) {
        ListNode *cur=dummy;
        ListNode *tmp=new ListNode(val);
        while(cur->next!=nullptr)
        cur=cur->next;
        cur->next=tmp;
        tmp->next=nullptr;
        size++;
    }
    
    void addAtIndex(int index, int val) {
        if(index<0||index>size)
        return ;
        ListNode *cur=dummy;
        ListNode *tmp=new ListNode(val);
        while(index--)
        cur=cur->next;        
        tmp->next=cur->next;
        cur->next=tmp;
        size++;
    }
    
    void deleteAtIndex(int index) {
        if(index<0||index>size-1)
        return ;
        ListNode *cur=dummy;
        while(index--)
        cur=cur->next;
        
        cur->next=cur->next->next;
        size--;
    }
private:
    int size;
    ListNode *dummy;
};

 206. 反转链表 - 力扣(Leetcode)

三个指针转转转,注意顺序,保留好cur->next就行了

class Solution {
public:
    ListNode* reverseList(ListNode* head) {
    ListNode *cur=head;
    ListNode *tmp;
    ListNode *pre=nullptr;
    while(cur!=nullptr)
    {
        tmp=cur->next;
        cur->next=pre;
        pre=cur;
        cur=tmp;
    }    
    return pre;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值