[Leetcode]-Min Stack
来源:互联网 发布:淘宝优惠券在哪里看 编辑:程序博客网 时间:2024/06/16 12:39
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.
题目:实现一个栈,拥有pop,push,top,getmin操作。
结题思路:pop,push,top很基本的,getmin的意思必须在栈顶返回栈中最小的元素,那么很容易想到,既然必须在栈顶访问到整个栈中的最小元素,因为是栈所以不可能是存在遍历操作的,即使使用链表实现(原理上可以,但从栈的角度出发不能),因此在push的时候就必须将最小元素放在栈顶。那么这样就简单了,每次都比较新元素element和栈顶的元素data,将较小者放入栈顶。
struct node { int min; int data; struct node* next;};typedef struct { struct node *top;} MinStack;void minStackCreate(MinStack *stack, int maxSize) { stack->top = NULL;}void minStackPush(MinStack *stack, int element) { struct node* p = (struct node*)malloc(sizeof(struct node)); p->data = element; if(stack->top == NULL) p->min = element; else { if(stack->top->min > element) p->min = element; else p->min = stack->top->min; } p->next = stack->top; stack->top = p;}void minStackPop(MinStack *stack) { struct node* p = NULL; p = stack->top; stack->top = p->next; free(p);}int minStackTop(MinStack *stack) { return stack->top->data;}int minStackGetMin(MinStack *stack) { return stack->top->min;}void minStackDestroy(MinStack *stack) { while(stack->top != NULL) minStackPop(stack);}
1 0
- LeetCode[stack]: Min Stack
- [leetcode][stack] Min Stack
- 【Leetcode】Min Stack
- Leetcode: Min Stack
- leetcode Min stack
- Min Stack -- LeetCode
- Leetcode: Min Stack
- 【LeetCode】Min Stack
- leetcode Min Stack
- leetcode--Min Stack
- [Leetcode]Min stack
- leetcode:Min Stack
- leetcode 之 Min Stack
- leetcode Min Stack
- LeetCode(155) Min Stack
- [LeetCode]Min Stack
- leetcode:Min Stack
- leetcode - Min Stack
- JSON数据的生成与解析
- Objective-C 深拷贝与浅拷贝
- halcon一维测量
- ROS安装USB摄像头
- OCR File and Voting Disk Administration by Example - (Oracle 10g)
- [Leetcode]-Min Stack
- Stanford UFLDL教程 反向传播算法(BP算法)
- C++模板递归深度的思考
- Android下如何mount光盘镜像ISO文件 (2012-03-06 22:01:29)
- 第5天-sql计算字段的创建与基础函数的使用
- 【莫比乌斯反演】【bzoj2301】problem b
- 编写测试用例
- Rotate Array
- PLSQL developer 连接不上64位Oracle 的解决方法