两个堆栈实现队列及排序
package com.ranger.demo;
import java.util.Stack;
/**
* Created by on 2019/2/11.
*/
public class TestStack {
Stackstack1 =new Stack();
Stackstack2 =new Stack();
/**
* 初始化,插入
* @param num
*/
private void push(int num) {
stack1.push(num);
}
/**
* 实现队列
* @return
*/
private int pop() {
Integerp =null;
if (!stack2.isEmpty()) {
p =stack2.pop();
}else {
while (!stack1.isEmpty()) {
p =stack1.pop();
stack2.push(p);
}
if (!stack2.empty()) {
p =stack2.pop();
}
}
return p;
}
/**
* 实现排序
* @param stack
* @return
*/
private Stacksort(Stack stack) {
Stack tempStack =new Stack<>();
while (!stack.isEmpty()) {
int cur = stack.pop();
while (!tempStack.isEmpty() && tempStack.peek() < cur) {
stack.push(tempStack.pop());
}
tempStack.push(cur);
}
return tempStack;
}
public static void main(String args[]) {
TestStack testStack =new TestStack();
int a[] = {2, 5, 6, 1, 10};
System.out.println("----入栈----");
for (int b : a) {
testStack.push(b);
System.out.print(b +"\t");
}
System.out.println("\n----队列先进先出----");
int s = a.length;
for (int i =0; i < s; i++) {
System.out.print(testStack.pop() +"\t");
}
for (int b : a) {
testStack.push(b);
}
System.out.println("\n----排序----");
Stack sort = testStack.sort(testStack.stack1);
while (!sort.isEmpty()) {
System.out.print(sort.pop() +"\t");
}
}
}
网友评论