堆栈的原理
栈(stack)又名堆栈,一个数据集合,可以理解为只能在一端进行插入或删除操作的列表。其限制是仅允许在表的一端进行插入和删除运算。这一端被称为栈顶,相对地,把另一端称为栈底。
栈就是一个桶,后放进去的先拿出来,它下面本来有的东西要等它出来之后才能出来(先进后出)
栈的基本操作:
进栈(压栈):push
出栈:pop
java实现堆栈
(1)通过List实现一个堆栈:
public class Stack_List {
public static void main(String[] args){
System.out.println("通过List实现一个堆栈:");
Stack stack = new Stack();
stack.push(1);
stack.push(2);
stack.push(3);
System.out.println(stack.pop());
System.out.println(stack.pop());
stack.push(4);
stack.push(5);
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());
}
}
//使用集合定义一个堆栈
class Stack {
List<Integer> list = new ArrayList<Integer>();
int index = 0; //下标
//入栈
public void push(int n){
list.add(n);
index++;
}
//出栈
public int pop(){
if(!list.isEmpty()){
index--;
return list.remove(index);
}
return -1;
}
}
(2)通过数组实现一个堆栈:
public class Stack_Array {
public static void main(String[] args){
System.out.println("数组实现一个堆栈:");
Stack stack = new Stack();
stack.push(1);
stack.push(2);
System.out.println(stack.pop());
System.out.println(stack.pop());
stack.push(3);
stack.push(4);
stack.push(5);
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());
}
}
//使用数组定义一个堆栈
class Stack {
int[] a = new int[5];
int i = 0; //数组下标
//入栈
public void push(int n){
a[++i] = n;
}
//出栈
public int pop(){
if(i>0){
return a[i--];
}
return -1;
}
}
(3)通过两个队列实现一个堆栈:
public class Stack_Queue {
public static void main(String[] args) {
System.out.println("两个队列实现一个堆栈:");
Stack stack = new Stack();
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
System.out.println(stack.pop());
System.out.println(stack.pop());
stack.push(5);
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());
}
}
//两个队列实现一个堆栈
class Stack {
Queue<Integer> queueA = new ArrayDeque<Integer>();
Queue<Integer> queueB = new ArrayDeque<Integer>();
//入栈
public void push(int n){
queueA.add(n);
}
//出栈
public int pop(){
//如果queueA为空,queueB有元素, 将queueB的元素依次放入queueA中,直到最后一个元素,我们弹出。
if(queueA.isEmpty()){
while (queueB.size() > 1) {
queueA.add(queueB.poll());//poll()移出并返回队列的头元素,如果队列为空,则返回null
}
return queueB.poll();
}
if(queueB.isEmpty()){
while (queueA.size() > 1) {
queueB.add(queueA.poll());
}
return queueA.poll();
}
return -1;
}