代码随想录训练营打卡第三天:链表

day 3:链表

首先是链表的定义要会自己写:

struct ListNode{
  int val;
  ListNode *next;
  ListNode(int x):val(x),next(NULL){}
};

203:移除链表元素

class Solution {
public:
    ListNode* removeElements(ListNode* head, int val) {
        //定义虚拟头节点
        ListNode* dummyhead = new ListNode(-1);
        dummyhead->next = head;
        //特判
        if(head == nullptr) return nullptr;

        ListNode* cur = dummyhead;
        while(cur->next != nullptr){
            if(cur->next->val == val){
                cur->next = cur->next->next;
                //等于的时候不跳,不等时候才跳
            }else{
               cur = cur->next; 
            }
        }
        return dummyhead->next;
    }
};

707:老问题:设计链表:

class MyLinkedList {
public:
    //定义结构体:
    struct LinkedList{
        int val;
        LinkedList *next;
        LinkedList( int val): val(val),next(nullptr){}
    };

    MyLinkedList() {
        _dummyhead = new LinkedList(0);
        _size = 0;
    }
    
    int get(int index) {
        if(index > (_size -1 ) || index <0){
            return -1;
        }
        LinkedList* cur = _dummyhead->next;
        while(index--){
            cur = cur->next;
        }
        return cur->val;
    }
    
    void addAtHead(int val) {
        LinkedList* newNode = new LinkedList(val);
        newNode->next = _dummyhead->next;
        _dummyhead->next = newNode;
        _size++;
    }
    
    void addAtTail(int val) {
        LinkedList* newNode = new LinkedList(val);
        LinkedList* cur = _dummyhead;
        while(cur->next != nullptr){
            cur = cur->next;
        }
        cur->next = newNode;
        _size++;
    }
    
    void addAtIndex(int index, int val) {
        if(index > _size || index < 0 ){
            return;
        }
        LinkedList* newNode = new LinkedList(val);
        LinkedList* cur = _dummyhead;
        while(index--){
            cur = cur->next;
        }
        newNode->next = cur->next;
        cur->next = newNode;
        _size++;
    }   
    
    void deleteAtIndex(int index) {
        if(index >= _size || index < 0){
            return ;
        }
        LinkedList* cur = _dummyhead;
        while(index--){
            cur = cur->next;
        }
        LinkedList* temp = cur->next;
        cur->next = cur->next->next;
        delete temp;
        _size--;
    }
//链表的两个属性
private:
    int _size;
    LinkedList *_dummyhead;
};

206:翻转链表:

class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        ListNode* pre = nullptr;
        ListNode* cur= head;

        while(cur){
            ListNode* temp = cur->next;
            cur->next = pre;
            pre = cur;
            cur = temp;
        }
        return pre;
    }
};

/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值