应用2个栈实现队列
- 题目形容
用两个栈来实现一个队列,实现队列的Push和Pop操作。队列中的元素为int类型。
- 示例
无 须要先明确2点:队列是先进先出的,栈是先进后出的
- 解题思路
须要两个栈Stack1和Stack2,push的时候间接push进Stack1。pop须要判断Stack1和Stack2中元素的状况,Stack1空的话,间接从Stack2 pop,Stack1不空的话,把Stack1的元素push进入Stack2,而后pop Stack2的值。
1.push: 间接push进stack1。须要pop全副stack2,才开始将stack1元素放进stack2中
2.pop:if stack2 不为空,间接pop stack2;if stack2 为空,须要将stack1元素全副放入stack2中,而后pop
- Java实现
import java.util.Stack; public class Solution { Stack<Integer> stack1 = new Stack<Integer>(); Stack<Integer> stack2 = new Stack<Integer>(); public void push(int node) { stack1.push(node); } public int pop() { if (stack1.isEmpty() && stack2.isEmpty()){ return -1; } if (stack2.isEmpty()){ while (!stack1.isEmpty()){ stack2.push(stack1.pop()); } } return stack2.pop(); }}
- Python实现
# -*- coding:utf-8 -*-class Solution: def __init__(self): self.stack1 = [] self.stack2 = [] def push(self, node): # write code here self.stack1.append(node) def pop(self): # return xx if not self.stack1 and not self.stack2: return if not self.stack2: #如果stack2为空 while self.stack1: self.stack2.append(self.stack1.pop()) return self.stack2.pop()
如果您感觉本文有用,请点个“在看”