首页 > 代码库 > Min Stack
Min Stack
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
- push(x) -- Push element x onto stack.
- pop() -- Removes the element on top of the stack.
- top() -- Get the top element.
- getMin() -- Retrieve the minimum element in the stack.
C: #include<stdlib.h> #include<stdio.h> struct node { int data; struct node* down; }; typedef struct node node; struct stack { node* top; int size; }; typedef struct stack Stack; Stack* EmptyStack() { Stack *top = (Stack*)malloc(sizeof(Stack*)); if(top) { top->top = NULL; top->size = 0; } return top; } void push(Stack* stack,Stack* minstack,int x) { node* newtop=(node *)malloc(sizeof(node)); newtop->data=http://www.mamicode.com/x;>C++ class MinStack { private: stack<int> datastack; stack<int> minstack; public: void push(int x) { datastack.push(x); if(minstack.empty() || x<=minstack.top()) minstack.push(x); } void pop() { int data=http://www.mamicode.com/datastack.top();>Min Stack
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。