Question: Design a Data Structure SpecialStack that supports all the stack operations like push(), pop(), isEmpty(), isFull() and an additional operation getMin() which should return minimum element from the SpecialStack. All these operations of SpecialStack must be O(1). To implement SpecialStack, you should only use standard Stack data structure and no other data structure like arrays, list, .. etc.

Example:

Consider the following SpecialStack
16 --> TOP
15
29
19
18 When getMin() is called it should return 15,
which is the minimum element in the current stack. If we do pop two times on stack, the stack becomes
29 --> TOP
19
18 When getMin() is called, it should return 18
which is the minimum in the current stack.
  • 解答
# Class to make a Node
class Node:
# Constructor which assign argument to nade's value
def __init__(self, value):
self.value = value
self.next = None # This method returns the string representation of the object.
def __str__(self):
return "Node({})".format(self.value) # __repr__ is same as __str__
__repr__ = __str__ class Stack:
# Stack Constructor initialise top of stack and counter.
def __init__(self):
self.top = None
self.count = 0
self.minimum = None # This method returns the string representation of the object (stack).
def __str__(self):
temp = self.top
out = []
while temp:
out.append(str(temp.value))
temp = temp.next
out = '\n'.join(out)
return ('Top {} \n\nStack :\n{}'.format(self.top,out)) # __repr__ is same as __str__
__repr__=__str__ # This method is used to get minimum element of stack
def getMin(self):
if self.top is None:
return "Stack is empty"
else:
print("Minimum Element in the stack is: {}" .format(self.minimum)) # Method to check if Stack is Empty or not
def isEmpty(self):
# If top equals to None then stack is empty
if self.top == None:
return True
else:
# If top not equal to None then stack is empty
return False # This method returns length of stack
def __len__(self):
self.count = 0
tempNode = self.top
while tempNode:
tempNode = tempNode.next
self.count+=1
return self.count # This method returns top of stack
def peek(self):
if self.top is None:
print ("Stack is empty")
else:
if self.top.value < self.minimum:
print("Top Most Element is: {}" .format(self.minimum))
else:
print("Top Most Element is: {}" .format(self.top.value)) # This method is used to add node to stack
def push(self,value):
if self.top is None:
self.top = Node(value)
self.minimum = value elif value < self.minimum:
temp = (2 * value) - self.minimum
new_node = Node(temp)
new_node.next = self.top
self.top = new_node
self.minimum = value
else:
new_node = Node(value)
new_node.next = self.top
self.top = new_node
print("Number Inserted: {}" .format(value)) # This method is used to pop top of stack
def pop(self):
if self.top is None:
print( "Stack is empty")
else:
removedNode = self.top.value
self.top = self.top.next
if removedNode < self.minimum:
print ("Top Most Element Removed :{} " .format(self.minimum))
self.minimum = ( ( 2 * self.minimum ) - removedNode )
else:
print ("Top Most Element Removed : {}" .format(removedNode)) # Driver program to test above class
stack = Stack() stack.push(3)
stack.push(5)
stack.getMin()
stack.push(2)
stack.push(1)
stack.getMin()
stack.pop()
stack.getMin()
stack.pop()
stack.peek() # This code is contributed by Blinkii
  • 分析

https://www.geeksforgeeks.org/design-a-stack-that-supports-getmin-in-o1-time-and-o1-extra-space/

Design a stack that supports getMin() in O(1) time and O(1) extra space的更多相关文章

  1. [LeetCode] Min Stack 最小栈

    Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. pu ...

  2. 【leetcode】Min Stack -- python版

    题目描述: Design a stack that supports push, pop, top, and retrieving the minimum element in constant ti ...

  3. 【leetcode】Min Stack(easy)

    Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. pu ...

  4. [LeetCode] Min Stack

    Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. pu ...

  5. Java for LeetCode 155 Min Stack

    Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. pu ...

  6. LeetCode之Min Stack 实现最小栈

    LeetCode相关的网上资源比较多,看到题目一定要自己做一遍,然后去学习参考其他的解法. 链接: https://oj.leetcode.com/problems/min-stack/ 题目描述: ...

  7. leetcode 155. Min Stack --------- java

    Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. pu ...

  8. Min Stack [LeetCode 155]

    1- 问题描述 Design a stack that supports push, pop, top, and retrieving the minimum element in constant ...

  9. Min Stack

    Min Stack Design a stack that supports push, pop, top, and retrieving the minimum element in constan ...

随机推荐

  1. asp.net运行原理及机制

    当一个HTTP请求到服务器并被IIS接收到之后,IIS首先通过客户端请求的页面类型为其加载相应的.dll文件,然后在处理过程中将这条请求发送给能够处理这个请求的模块.在ASP.NET 3.5中,这个模 ...

  2. window下git代码推送

    https://blog.csdn.net/luosaosao/article/details/63684470

  3. 【AST篇】教你如何编写 Eslint 插件

    前言 虽然现在已经有很多实用的 ESLint 插件了,但随着项目不断迭代发展,你可能会遇到已有 ESLint 插件不能满足现在团队开发的情况.这时候,你需要自己来创建一个 ESLint 插件. 本文我 ...

  4. SpringBoot项目中遇到的BUG

    1.启动项目的时候报错 1.Error starting ApplicationContext. To display the auto-configuration report re-run you ...

  5. spring boot基础学习教程

    Spring boot 标签(空格分隔): springboot HelloWorld 什么是spring boot Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新 ...

  6. 配置 http 反向代理

    [root@nginx ~]# cd /etc/nginx/ 1 [root@nginx nginx]# cp nginx.conf nginx.conf.bak #备份一个原配置文件 2 [root ...

  7. 架构师必备,带你弄清混乱的JAVA日志体系!

    作者:孤独烟 出处:http://rjzheng.cnblogs.com/ 本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任 ...

  8. 286-基于6U VPX 的mSATA高性能数据存储板

    基于6U VPX 的mSATA高性能数据存储板 一.板卡概述 该产品系我司自主研发.基于标准6U VPX架构. 二.产品特性       最大存储容量8TB        读写方式RAID0 ,读写速 ...

  9. C/C++ 零碎知识点

    传递参数的一般指导原则: 对于使用传递的值而不做修改的函数: 如果数据对象很小,比如内置类型或者小型结构,按值传递. 如果数据对象是数组,只能使用指针,并将指针生命为指向const的指针. 如果数据对 ...

  10. Centos 7.5 双网卡内外网同时访问路由设置

    说明:服务器有两张网卡分别是eth0.eth1,eth0配置内网IP:192.168.1.1/24,eth1配置外网IP:10.1.1.1/24:要求192.168.0.0/16网段走网卡eth0,网 ...