数据结构实现系列

一、两个栈实现一个队列

class CQueue {
public:
    CQueue() {
    }
    stack s1, s2;
    
    void appendTail(int value) {
        s1.push(value);
    }
    
    int deleteHead() {
        if(!s2.empty()) {
            int tmp = s2.top();
            s2.pop();
            return tmp;
        }
        if(s1.empty()) return -1;
        while(!s1.empty()) {
            s2.push(s1.top());
            s1.pop();
        }
        int tmp = s2.top();
        s2.pop();
        return tmp;
    }
};

二、LC225. 用队列实现栈

class MyStack {
private:
    queue q;
public:
    /** Initialize your data structure here. */
    MyStack() {}
    
    /** Push element x onto stack. */
    void push(int x) {
        q.push(x);
    }
    
    /** Removes the element on top of the stack and returns that element. */
    int pop() {
        int ans = q.back();
        queue tmp;
        for(int i = q.size()-1; i > 0; i--) {
            tmp.push(q.front());
            q.pop();
        }
        q = tmp;
        return ans;
    }
    
    /** Get the top element. */
    int top() {
        return q.back();
    }
    
    /** Returns whether the stack is empty. */
    bool empty() {
        return q.empty();
    }
};

三、LC146. LRU缓存机制

class LRUCache {
private:
    int capacity_; //容量
    list> l; //一组存入list
    unordered_map>::iterator> m; //key->存储(key, val)对的list的迭代器
public:
    LRUCache(int capacity) {
        capacity_ = capacity;
    }
    
    int get(int key) {
        auto it = m.find(key);
        if(it == m.end()) return -1;

        auto lit = it->second; //取出第二项,就是链表迭代器
        l.splice(l.begin(), l, lit);  //将l中的lit迭代器指向的节点删除,并插入到l.begin()之前
        return lit->second;
    }
    
    void put(int key, int value) {
        auto it = m.find(key);
        if(it != m.end()) {  //如果已经存在key, 需要更新key的val, 并将节点提到最前面
            it->second->second = value;
            l.splice(l.begin(), l, it->second);
            return;
        }

        //以下讨论key不存在的情况
        if(l.size() == capacity_) {
            auto& node = l.back(); //返回最后一个元素, 赋值给一个引用变量
            m.erase(node.first); //根据节点的key值删除map中对应的key-value对
            l.pop_back(); //list l的最后一个元素删除,在此之前要把map中的key也删除!!!
        }

        l.push_front({key, value});
        m[key] = l.begin();
    }
};

四、面试题30. 包含min函数的栈

class MinStack {
public:
    /** initialize your data structure here. */
    MinStack() {
        //A = new stack();
        //B = new stack();
    }
    
    void push(int x) {
        A.push(x);
        if(B.empty() || x <= B.top()) {
            B.push(x);
        }
    }
    
    void pop() {
        if(!A.empty()) {
            //int top = A.top();
            if(A.top() == B.top()) { // == 错写成 = ...
                B.pop();
            }
            A.pop();
        }
    }
    
    int top() {
        return A.top();
    }
    
    int min() {
        return B.top();
    }
private:
    stack A;
    stack B;
};

 

你可能感兴趣的:(LeetCode,数据结构实现)