CareerCup-3.2

How would you design a stack which, in addition to push and pop, also has a function 
min which returns the minimum element? Push, pop and min should all operate in 
O(1) time

微软实习生一面就遇到了这个问题,当时想到的是笨办法。但是面试官一点点引导,终于想出来这么做。

#include <iostream>
using namespace std;
typedef int Data;
// Creating a Linked List:
struct Node
{
    Node(Data d=0):data(d){next = NULL;};
    Data data;
    Node* next;
};

class Stack
{
public:
    Stack():top(NULL){minNode = NULL;};
    void pop()
    {
        if(top != NULL)
        {
            Node* p = top;
            top = top->next;
            delete p;
            Node* m = minNode;
            minNode = minNode->next;
            delete m;
        }
    };
    Data peek()
    {
        if(top != NULL)
        {
            return top->data;
        } else {
            throw "Empty Stack";
        }
    };
    void push(Data data)
    {
        Node* d = new Node(data);
        d->next = top;
        top = d;
        if(minNode != NULL && minNode->data < data)
            data = minNode->data;
        Node *m = new Node(data);
        m->next = minNode;
        minNode = m;
    };
    Data min()
    {
        if(minNode == NULL)
            throw "Empty Stack";
        else
            return minNode->data;
    }; 
    bool isEmpty(){return top == NULL;};
private:
    Node* top;
    Node* minNode;
};

int main()
{
    Stack stack;
    stack.push(3);
    cout<<stack.min()<<endl;
    stack.push(2);
     cout<<stack.min()<<endl;
    stack.pop();
    cout<<stack.min()<<endl;
    system("pause");
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值