#include<iostream>
using namespace std;
class Stack
{
private:
int top;
int id;
char *arr[12];//栈中的元素存储于一个容量为12的指针数组里
public:
Stack(int id)
{
this->id=id;
top=0;//当栈中无元素时,top指针=0
}
~Stack()
{
cout<<"进入析构函数!"<<endl;
}
void push(char * element);//压入一个元素进栈顶
char *pop();//弹出栈顶元素
int getTop();//返回栈顶指针
void showTopValue();//输出栈中元素
};
void Stack::push(char * element)
{
arr[top++]=element;
}
char * Stack::pop()
{
return arr[--top];
}
int Stack::getTop()
{
return top;
}
void Stack::showTopValue()
{
for(int i=top-1;i>-1;i--)
{
cout<<"栈"<<id<<"中的值为:"<<arr[i]<<endl;//模拟元素出栈的输出...
}
}
int main()
{
Stack stack1(1);
Stack stack2(2);
stack1.push("January");//元素依次入栈
stack1.push("February");
stack1.push("March");
stack1.push("April");
stack1.push("May");
stack1.push("June");
stack1.push("July");
stack1.push("August");
stack1.push("September");
stack1.push("October");
stack1.push("November");
stack1.push("December");
stack1.showTopValue();
cout<<"***********************"<<endl;
if(stack2.getTop()==0)//判断栈2是否为空
{
while(stack1.getTop()!=0)//确保将栈1的所有元素压入栈2
{
stack2.push(stack1.pop());//核心代码,将栈1里的元素依次压入栈2
}
}
stack2.showTopValue();
/*
while(stack2.getTop()!=0)
{
cout<<"栈2中的值为:"<<stack2.pop()<<endl;
}*/
cout<<"两栈实现队列完毕!"<<endl;
cout<<stack1.getTop()<<endl;//最终top=0
cout<<stack2.getTop()<<endl;//最终top=12
}
用C++练下手哈,两个栈实现一个队列还是自己写感觉踏实点...
实现原理也就是将栈1的元素依次压入另外一个栈,然后弹出这个栈顶元素即可。