栈——设计一个有getmin功能的栈

题目:实现一个特殊的栈,在实现栈的基本功能的基础上,再实现返回栈中最小元素的操作。

要求:
1、pop、push、getMin操作的时间复杂度都是O(1)。
2、设计的栈类型可以输用现成的栈结构。


思路:使用两个栈,一个用来保存栈中的元素,另一个用于保存每步的最小值
 其实就是左神的思路啦~
代码:
package getmin;

import java.util.Stack;

import javax.management.RuntimeErrorException;

public class MyStack {
	private Stack<Integer> stackData;
	private Stack<Integer> stackMin;
	
	public MyStack(){
		this.stackData = new Stack<Integer>();
		this.stackMin = new Stack<Integer>();
	}
	
	public void push(int newNum){
		if(this.stackMin.isEmpty()){
			this.stackMin.push(newNum);
		}else if(newNum <= this.getmin()){
			this.stackMin.push(newNum);
		}else{
			this.stackData.push(newNum);
		}
	}
	
	public int pop(){
		if(this.stackData.isEmpty()){
			throw new RuntimeException("your stack is empty");
		}
		int value = this.stackData.pop();
		if(value == this.getmin()){
			this.stackMin.pop();
		}
		return value;
	}
	
	public int getmin(){
		if(this.stackMin.isEmpty()){
			throw new RuntimeException("your stack is empty");
		}
		return this.stackMin.peek();
	}

public static void main(String args[])
{
	MyStack sta = new MyStack();
	sta.push(3);
	sta.push(4);
	sta.push(2);
	sta.push(1);
	sta.pop();
	int min = sta.getmin();
	System.out.println(min);
}

}









好的,下面是关于用C语言编写单调队列和单调的一些基本思路: 单调队列: 单调队列是一种能够在O(1)时间内完成以下操作的队列:在队尾添加元素、在队首删除元素、查找队列中的最小(或最大)元素。 在C语言中,可以使用数组模拟队列,并通过双端队列的思想来实现单调队列。具体实现时,我们可以使用一个数组来存储队列中的元素,并使用两个指针front和rear分别指向队首和队尾元素。为了实现单调性,我们需要维护一个递增(或递减)的队列,即队列中的元素按照一定的顺序排列。为了实现这个目标,我们可以在插入元素时,从队尾开始遍历队列,将所有比插入元素小的元素都出队,最后将插入元素入队。这样,我们就可以保证队列中的元素是单调递增的。查找最小元素时,只需要返回队首元素即可。 以下是用C语言实现单调队列的基本代码: ```c #include <stdio.h> #define MAXSIZE 1000 int queue[MAXSIZE]; // 队列 int front = 0, rear = 0; // 队首和队尾指针 // 判断队列是否为空 int isEmpty() { return front == rear; } // 判断队列是否已满 int isFull() { return rear == MAXSIZE; } // 在队尾添加元素 void enqueue(int x) { while (rear > front && queue[rear - 1] > x) { rear--; } queue[rear++] = x; } // 在队首删除元素 void dequeue() { if (!isEmpty()) { front++; } } // 查找队列中的最小元素 int getMin() { if (!isEmpty()) { return queue[front]; } return -1; } int main() { enqueue(3); enqueue(1); enqueue(5); dequeue(); printf("%d\n", getMin()); return 0; } ``` 单调: 单调是一种能够在O(1)时间内完成以下操作的:在顶添加元素、在顶删除元素、查找中的最小(或最大)元素。 与单调队列类似,我们也可以使用数组模拟,并通过的特性来实现单调。为了实现单调性,我们需要维护一个递增(或递减)的,即中的元素按照一定的顺序排列。为了实现这个目标,我们在插入元素时,从顶开始遍历,将所有比插入元素小的元素出栈,最后将
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值