Java与算法(1)

Java与算法(1)

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

要求:

1 pop,push,getMin操作的时间复杂度都是O(1) 2 设计的栈类型可以使用现成的栈结构

public class Stack_getMIn {
	 Stack<Integer> stack_data ;
	 Stack<Integer> stack_min ;
	 
	 public Stack_getMIn(Stack<Integer> stack_data,Stack<Integer> stack_min) {
		 this.stack_data = stack_data;
		 this.stack_min = stack_min;
	}
	
	 public void push(int newNum) {
		 		if (stack_min.isEmpty()) {
					stack_min.push(newNum);
				} else if (stack_min.peek()>newNum) {
						stack_min.push(newNum);
				}
		 		stack_data.push(newNum);
	}
	 
	 
	 public int pop() {
		int value = stack_data.peek();
		if (stack_min.peek()==value) {
			stack_min.pop();
		}
		return value;
	}
	 
	 public int getMin() {
		 return stack_min.peek();
	}
	

	public static void main(String[] args) {
			Stack<Integer> data = new Stack<>();
			Stack<Integer> min = new Stack<>();
			
			Stack_getMIn stack_getMIn = new Stack_getMIn(data,min);
			stack_getMIn.push(5);
			stack_getMIn.push(20);
			stack_getMIn.push(0);
			System.out.println(stack_getMIn.getMin());
			stack_getMIn.pop();
			System.out.println(stack_getMIn.getMin());
			
 	}

}

题目:

编写一个类,使用两个栈实现队列,支持队列的基本操作(add,poll,peek)

public class StackToQueue {
	Stack<Integer> s1 ;
	Stack<Integer> s2;
	public StackToQueue(Stack<Integer> s1,Stack<Integer> s2) {
				this.s1 = s1;
				this.s2 = s2;
	}
	
	public void add(int num) {
		s1.add(num);
		
	}
	
	public int peek() {
			if (s2.isEmpty()) {
				while (!s1.isEmpty()) {
					s2.push(s1.pop());
				}
			}
			return s2.peek();
	}
	
	public int pool() {
		if (s2.isEmpty()) {
			while (!s1.isEmpty()) {
				s2.push(s1.pop());
			}
		}
		return s2.pop();
	}

	public static void main(String[] args) {
			Stack<Integer> s1 = new Stack<>();
			Stack<Integer> s2 = new Stack<>();
			StackToQueue stackToQueue = new StackToQueue(s1, s2);
			stackToQueue.add(5);
			stackToQueue.add(4);
			stackToQueue.add(3);
			System.out.println(stackToQueue.peek());
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值