栈实现队列:
#include<iostream>
#include<stack>
template<class T>class Queue
{
std::stack<T> st1, st2;
public:
void enqueue(T head)
{
st1.push(head);
}
T pop()
{
while (!st1.empty())
{
st2.push(st1.top());
st1.pop();
}
T tail = st2.top();
st2.pop();
while (!st2.empty())
{
st1.push(st2.top());
st2.pop();
}
return tail;
}
};
int main()
{
Queue<int> qint;
for (int i = 1; i < 10; i++)
{
qint.enqueue(i);
}
std::cout << qint.pop() << std::endl;
system("pause");
return 0;
}
链表实现栈:
#include<iostream>
#include<list>
template<class T>class Stake
{
std::list<T> tempList;
public:
void push(T e)
{
tempList.push_front(e);
}
T pop()
{
T tempEl = tempList.front();
tempList.pop_front();
return tempEl;
}
int length()
{
int num(0);
std::list<T> lList;
while (!tempList.empty())
{
num++;
lList.push_front(tempList.front());
tempList.pop_front();
}
while (!lList.empty())
{
tempList.push_front(lList.front());
lList.pop_front();
}
return num;
}
};
int main()
{
Stake<int> testSt;
for (int i = 0; i < 10; i++)
{
testSt.push(i);
}
//std::cout << testSt.length() << std::endl;
for (size_t i = 0; i < testSt.length();)
{
std::cout << testSt.pop() << std::endl;
}
system("pause");
return 0;
}