思路:
主要抓住栈的“先进后出”和队列的“先进先出”。
s1是入栈的,s2是出栈的。
- 入队列,直接压到s1是就行了。
- 出队列,先把s1中的元素全部出栈压入到s2中,弹出s2中的栈顶元素;再把s2的所有元素全部压回s1中。
代码实现:
#include
<iostream>
using
namespace
std;
template
<class
T>
class
Stack
{
public
:
Stack():_stack(NULL),_capacity(0),_top(0)
{
}
Stack(
int
capacity):_stack(NULL),_top(0)
{
assert(capacity > 0);
//确保指定的栈的初始容量大于零
_stack =
new
T[capacity];
}
~Stack()
{
delete[] _stack;
_top = 0;
_capacity = 0;
}
void
Push(T elem)
{
if(_top == _capacity)//
若当前栈已满,则进行扩容
{
T* temp =
new
T[_capacity*2+1];
_capacity = _capacity*2+1;
memcpy(temp,_stack,
sizeof(T)*_top);
delete[] _stack;//
将当前的栈空间释放
_stack = temp;
}
_stack[_top++] = elem;
}
void
Pop()
{
if(Empty())
{
return;
}
_stack[--_top] = NULL;
}
void
Pop(T& elem)
{
elem = _stack[--_top];
stack[_top] = NULL;
}
const
T& Top()
{
return
_stack[_top - 1];
}
bool
Empty()
{
return
_top == T();
}
private
:
T* _stack;
//定义指向栈数组的指针
int
_capacity;//
栈的容量
int
_top;//
栈顶的下一个位置处下标
};
template
<class
T>
class
Queue
{
public
:
Queue()
{
}
~Queue()
{}
bool
Empty()
{
return(s1.Empty()&&s2.Empty());
}
void
Push(T elem)
{
if(s1.Empty()&&!s2.Empty())
{
while(!s2.Empty())
{
s1.Push(s2.Top());
s2.Pop();
}
s1.Push(elem);
}
else
s1.Push(elem);
}
void
Pop()
{
if(Empty())
{
cout<<
"Queue is not Pop"
<<endl;
exit(-1);
}
if(s1.Empty()&&!s2.Empty())
{
s2.Pop();
}
if(!s1.Empty()&&s2.Empty())
{
while(!s1.Empty())
{
s2.Push(s1.Top());
s1.Pop();
}
s2.Pop();
}
}
const
T& Top()
{
if(Empty())
{
cout<<
"Queue is NULL!!!"
<<endl;
exit(-1);
}
while(!s1.Empty())
{
s2.Push(s1.Top());
s1.Pop();
}
T tmp = s2.Top();
while(!s2.Empty())
{
s1.Push(s2.Top());
s2.Pop();
}
return
tmp;
}
void
Print()
{
while(!s1.Empty())
{
s2.Push(s1.Top());
s1.Pop();
}
while(!s2.Empty())
{
cout<<s2.Top()<<
" ";
s2.Pop();
}
cout<<endl;
}
private
:
Stack<T> s1;
Stack<T> s2;
};
int
main()
{
Queue<
int> q1;
for(int i=0;i<100;++i)
{
q1.Push(i);
}
{
q1.Push(i);
}
q1.Pop;
q1.Print();
system(
"pause");
return
0;
}

被折叠的 条评论
为什么被折叠?



