代码1
/**俩个栈实现一个队列
*
*/
class twolink{
testlink1 t1=new testlink1();
testlink1 t2=new testlink1();
int top=0;//t1.elem的top
int top1=0;//t2.elem的top
class testlink1{
int []elem;
public testlink1(){
this(10);
}
public testlink1(int size) {
this.elem=new int [size];
// TODO Auto-generated constructor stub
}
//
}
//判断是否为空
public boolean isempt(){
if(this.top==0){
return true;
}
return false;
}
//入队
public void push(int val){
t1.elem[this.top]=val;//直接把val的值给t1.elem[this.top]
this.top++; }
//出队
public void pop(){
if(isempt()){
return ;
}
for(int i=0;i<top;i++){
t2.elem[top-i-1]=t1.elem[i];//把t1.elem的元素倒序给t2.elem
top1=this.top;
}
top1--;//t2进行出栈
for(int j=0;j<top1;j++){
t1.elem[top1-j-1]=t2.elem[j];//再把t2.elem的元素倒序给t1.elem这样就把t1.elem的第一个元素删除了
this.top=top1;
}
}
public void show(){
for(int i=0;i<this.top;i++){
System.out.println(t1.elem[i]);
}
}
public void gettop(){
System.out.println("队内第一个元素为"+t1.elem[0]);
}
}
public class Test2 {
public static void main(String[] args) {
twolink t1=new twolink();
for (int i=0;i<6;i++){
t1.push(i);
}
t1.show();
System.out.println("====");
t1.pop();
t1.show();
System.out.println("==出队后==");
System.out.println(t1.isempt());
t1.gettop();
// TODO Auto-generated method stub
}
}
运行结果
0
1
2
3
4
5
====
1
2
3
4
5
==出队后==
false
队内第一个元素为1
代码2
class stack{
int top;
int []elem;
public stack(){
this(10);
}
public stack(int size) {
this.elem=new int [size];
this.top=0;
// TODO Auto-generated constructor stub
}
//栈是否为满
public boolean isfull()
{
if(this.top==this.elem.length){
return true;
}
return false;
}
//入栈
public boolean push(int val){
if((isfull())){
return false;
}
this.elem[top]=val;
this.top=top+1;
return true;
}//是否为空
public boolean isempty(){
if(this.top==0){
return true;
}
return false;
}
//出栈
public int pop() {
//先判断是否为空
if(isempty()){
return -1;
}
int num=elem[top-1];
this.top--;
return num;
//return this.elem[--top];
//返回当前栈顶减一位置的的元素,并且栈顶往下减一。
}
//得到栈顶的元素
public int gettop(){
if(isempty()){
return -1;
}
return this.elem[this.top-1];//不能改变top的值,不能进行--top
}
public void show(){
for (int i=0;i<this.top;i++){
System.out.println(this.elem[i]);
}
}
}
/*
* 俩个栈实现一个队列
* */
public class test1 {
public static void enterqueue(stack s1,int val)
{s1.push(val);
}
public static int pop(stack s1,stack s2){
int num=0;
while(!s1.isempty()){
s2.push(s1.pop());//先将s1的元素给s2
}
num=s2.pop();//让s2出栈,并把这个值赋给num
while(!s2.isempty()){//把s2剩下的值赋给s1
s1.push(s2.pop());
}
return num;//返回num
}
public static void main(String[] args) {
stack t1=new stack();
stack t2=new stack();
enterqueue(t1,5);
enterqueue(t1,6);
enterqueue(t1,7);
t1.show();
System.out.println(pop(t1,t2));
System.out.println(pop(t1,t2));
System.out.println(pop(t1,t2));
System.out.println(pop(t1,t2));
// TODO Auto-generated method stub
}
}