1.队列:先进先出;栈:先进后出
2.栈提供push和pop等等接口,所有元素必须符合先进后出的规则,所以栈不提供走访功能,也不提供提迭代器,不像是set或者map提供迭代器来遍历所有元素。
3.栈是以底层容器完成其所有的工作,对外提供统一的接口,底层容器是可插拔的(也就是说我们可以控制使用哪种容器来实现栈的功能)。
4.栈的内部结构,栈的底层实现可以是vector,deque,list 都是可以的, 主要就是数组和链表的底层实现。
用栈实现队列Leetcode232
题目:
使用栈实现队列的下列操作:
push(x) – 将一个元素放入队列的尾部。
pop() – 从队列首部移除元素。
peek() – 返回队列首部的元素。
empty() – 返回队列是否为空。
注意事项:
1.需要输入与输出两个栈来一起实现
2.判断队列为空只需要判断两个栈都为空即可
3.用栈实现队列的pop操作,需要将输入栈中所有的元素都先放入输出栈中,再对输出栈进行操作!!注意是所有的元素,所以应该用while进行判断。
4.注意一下栈的实现。
class MyQueue {
//push:将一个元素放在队列尾部
//pop:从队列首部移除元素
//peek:返回队列首部元素
//empty:返回队列是否为空
Stack<Integer> stackIN;
Stack<Integer> stackOut;
public MyQueue() {
stackIN=new Stack<>();//负责进栈
stackOut=new Stack<>();//负责出栈
}
//push element x to the back of queue
public void push(int x) {
stackIN.push(x);
}
//remove the element from in front of queue and return that elements
public int pop() {
dumpstackIn();
return stackOut.pop();
}
//如果stackOut 为空,那么将StackIn中的元素全部放到stackout中
private void dumpstackIn(){
if(! stackOut.isEmpty())return;
while(!stackIN.isEmpty()){
stackOut.push(stackIN.pop());
}
}
//pop 和 peek有啥区别啊???
public int peek() {
dumpstackIn();
return stackOut.peek();
//Java有自己的peek操作
}
public boolean empty() {
return stackIN.isEmpty() && stackOut.isEmpty();
}
}
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue obj = new MyQueue();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.peek();
* boolean param_4 = obj.empty();
*/
用队列实现栈Leetcode225
题目:
请你仅使用两个队列实现一个后入先出(LIFO)的栈,并支持普通栈的全部四种操作(push、top、pop 和 empty)。
实现 MyStack 类:
void push(int x) 将元素 x 压入栈顶。
int pop() 移除并返回栈顶元素。
int top() 返回栈顶元素。
boolean empty() 如果栈是空的,返回 true ;否则,返回 false 。
注意事项:
1.可以用1个队列其实就可以实现,一刷先用两个队列来实现。
代码:
class MyStack {
//使用两个队列来实现栈
Queue<Integer> queue1;//和栈中保持一样元素的队列
Queue<Integer> queue2;//辅助队列
public MyStack() {
queue1=new LinkedList<>();
queue2=new LinkedList<>();
}
public void push(int x) {
queue2.offer(x);
while(!queue2.isEmpty()){
queue2.offer(queue1.poll());
}
Queue<Integer>queueTemp;
queueTemp=queue1;
queue1=queue2;
queue2=queueTemp;
//最后交换queue1和queue2,将元素都放在queue1中
}
public int pop() {
return queue1.poll();
}
public int top() {
return queue1.peek();
}
public boolean empty() {
return queue1.isEmpty();
}
}
/**
* Your MyStack object will be instantiated and called as such:
* MyStack obj = new MyStack();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.top();
* boolean param_4 = obj.empty();
*/
PS:感觉还行,我还能继续肝!!!加油!!