代码随想录day3

203.移除链表元素

确实没想到用递归的方式做,感觉直接写的话比较简单容易理解。  
class Solution {
public:
    ListNode* removeElements(ListNode* head, int val) 
    {
        ListNode*dummy= new ListNode(0);
        dummy->next=head;
        ListNode*cur=dummy;
        while(cur->next!=NULL)
        {
            if(cur->next->val==val)
            {
                cur->next=cur->next->next;
            }
            else cur=cur->next;
        }
        return dummy->next;
    }
};

707.设计链表  

写起来是有点复杂的

class MyLinkedList {
public:
    struct listnode{
        int val;
        listnode *next;
        listnode(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;
        listnode* cur=dummy;
        while(index--)
        {
            cur=cur->next;
        }
        return cur->next->val;
    }

    void addAtHead(int val) 
    {
        listnode* cur=new listnode(val);
        cur->next=dummy->next;
        dummy->next=cur;
        size++;
    }

    void addAtTail(int val) {
        listnode* cur=dummy;
        while(cur->next!=NULL)
        {
            cur=cur->next;
        }
        listnode* node=new listnode(val);
        cur->next=node;
        size++;
    }

    void addAtIndex(int index, int val) 
    {
        if(index>size) return;
        else if(index==size) addAtTail(val);
        else
        {
            listnode* cur=dummy;
            while(index--)
            {
                cur=cur->next;
            }
            listnode* node=new listnode(val);
            node->next=cur->next;
            cur->next=node;
            size++;
        }
    }
    void deleteAtIndex(int index) {
        if (index >= size || index < 0) {
            return;
        }
        listnode* cur = dummy;
        while(index--) {
            cur = cur ->next;
        }
        listnode* tmp = cur->next;
        cur->next = cur->next->next;
        delete tmp;
        tmp=nullptr;
        size--;
    }
private:
    int size;
    listnode* dummy;
};

 206.反转链表 

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

你可能感兴趣的:(c++,数据结构,leetcode,算法)