数组模拟实现常用数据结构

单链表

1.指针实现:

class MyLinkedList {
public:
    struct LinkedNode{
            int val;
            LinkedNode* next;
            LinkedNode(int val): val(val),next(nullptr){}
    };
 
    MyLinkedList() {
            _dummyhead = new LinkedNode(0);
            _size = 0;
    }
    
    int get(int index) {
            LinkedNode* cur = _dummyhead->next;//要创建一个cur指针来指向要操作的位置,不知道直接操作头指针
            if(index >= _size || index < 0) return -1;//最后一个节点是size-1
            while(index--){
                cur = cur->next;//cur指向向后移
            }
            return cur->val;
    }
    
    void addAtHead(int val) {
            LinkedNode*   newnode = new LinkedNode(val);
            newnode->next = _dummyhead->next;
            _dummyhead->next = newnode;
            _size++;
    }
    
    void addAtTail(int val) {
            LinkedNode* newnode = new LinkedNode(val);
            LinkedNode* cur = _dummyhead;
            while(cur->next != nullptr){
                cur = cur->next;
            }
            cur->next = newnode;
            _size++;
    }
    
    void addAtIndex(int index, int val) {
            LinkedNode* newnode = new LinkedNode(val);
            LinkedNode* cur = _dummyhead;
            if(index > _size) return;
            if(index < 0 ) index = 0;
            while(index--){
                cur = cur->next;
            }
            newnode->next = cur->next;
            cur->next = newnode;//
            _size++;
    }
    
    void deleteAtIndex(int index) {
            LinkedNode* cur = _dummyhead;
            if(index >= _size || index <0 ) return;//为什么是>=而不是>
            while(index--){
                cur = cur->next;
            }
            LinkedNode* tmp  = cur->next;
             cur->next = cur->next->next;
             delete tmp;
             tmp = nullptr;
             _size--;
    }
private:
    int _size;
    LinkedNode* _dummyhead; 
};

2.数组模拟 

int e[N], ne[N]; // 链表元素及下个结点的地址
int head;       // 头结点地址
int idx;        // 可用位置

/** 创建含头结点的单链表 */
void init() {
    head = 0;

    // 头结点
    e[0] = 0;       // 值为链表长度
    ne[0] = -1;     


    idx = 1;        // 第1个结点的下标从1开始
}

/** 向链表头部插入一个数 */
void insert_head(int x) {
    e[idx] = x;
    ne[idx] = ne[head];
    ne[head] = idx;
    idx++;

    e[0]++;     // 链表长度+1
}

/** 删除下标为k后面的数 */
void rem(int k) {
    ne[k] = ne[ne[k]];
    e[0]--;     // 链表长度-1
}

/** 在下标为k的位置后插入一个数 */
void insert(int k, int x) {
    e[idx] = x;
    ne[idx] = ne[k];
    ne[k] = idx;
    idx++;

    e[0]++;     // 链表长度+1
}

/** 遍历链表 */
void print() {
    for (int i = ne[head]; i != -1; i = ne[i]) cout << e[i] << " ";
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值