我們知道隊的特點是先進先出,元素只能從隊的尾部進入,只能從隊的尾部出來;棧的特點是先進先出,先進棧的元素被壓入棧底,後進入的元素覆在棧頂,出棧時也只能從棧的頂部出來。所以我們要借用兩個隊來實現棧的功能,先不用棧自身的屬性卻可以實現棧的屬性。(隊用鏈表來實現)
現有兩個隊,我們將他們分別記爲Qin,Qout,開始是將元素插入到Qin中,然後將將除了隊尾的元素全部保存到Qout中,保存的過程中依次將這些元素Pop掉,最後Qin中就只剩下開始時隊尾的那個元素,現在又將Qout中的元素取出來存到Qin中,這是Qin中的元素順序就改變了,開始的隊尾元素變成了隊頭元素其它的順序暫時不變,將Qin隊頭元素再將其Pop掉就可以了,一次類推就可以實現了棧的後進先出的功能。
(Queue.h)
class Node
{
public:
Node(const T& data) :_next(NULL), _data(data)
{}
Node<T>* _next;
T _data;
};
template <typename T>
class Queue
{
public:
Queue(Node<T>* head=NULL) :_head(head), _tail(NULL)
{
}
~Queue()
{
if (Empty())
{
Node<T>* cur = _head;
while (cur)
{
Node<T>* del;
del = cur;
cur = cur->_next;
delete del;
del = NULL;
}
_head = NULL;
_tail = NULL;
}
}
Queue(const Queue<T>& q)
{
Node<T>* cur = q._head;
while (cur)
{
Push(cur->_data);
cur = cur->_next;
}
}
Queue<T>& operator=(const Queue<T>& q)
{
if (this != &q)
{
delete _head;
_head = NULL;
Node<T>* cur = q._head;
while (cur)
{
Push(cur->_data);
cur = cur->_next;
}
}
return *this;
}
void Push(const T& d)
{
Node<T>* newNode = new Node<T> (d);
if (_head == NULL)
{
_head = newNode;
_tail = newNode;
}
else//實際是尾插
{
_tail->_next=newNode;
_tail = newNode;
}
}
void Pop()//頭部刪除
{
if (Empty())
{
if (_head == _tail)//一個節點
{
delete _head;
_head = NULL;
_tail = NULL;
}
else//多個節點
{
Node<T>* del = _head;
_head = _head->_next;
delete del;
del = NULL;
}
}
}
T& Back()
{
if (Empty())
{
return _tail->_data;
}
}
T& Front()
{
if (Empty())
{
return _head->_data;
}
}
bool Empty()
{
return _head != NULL;
}
size_t Size()
{
Node<T>* cur = _head;
size_t count = 0;
while (cur)
{
cur = cur->_next;
count++;
}
return count;
}
private:
Node<T>* _head;
Node<T>* _tail;
};
/*******************************************/
(Stack.h)
class Stack
{
public:
Stack()
{
}
~Stack()
{
}
Stack(const Stack<T>& s)
{
}
void Push(T d)
{
Qin.Push(d);
}
bool Empty()
{
return Qin.Empty();
}
void Pop()
{
if (Empty())
{
Qin.Pop();
}
}
T& Top()
{
if (Empty())
{
Swap();
T ret = Qin.Front();
return ret;
}
}
void Swap()//對兩個隊進行改變
{
while (Qin.Size() > 1)
{
Qout.Push(Qin.Front());
Qin.Pop();
}
while (Qout.Empty())
{
Qin.Push(Qout.Front());
Qout.Pop();
}
}
private:
Queue<T> Qin;//最開始將元素放在Qin中
Queue<T> Qout;//橋樑作用,用於改變Qin保存元素的工具
};
/************************************/
void test()//輸出檢驗
{
Stack<int> s1;
s1.Push(1);
s1.Push(3);
s1.Push(5);
s1.Push(7);
cout << s1.Top() << endl;
s1.Pop();
cout << s1.Top() << endl;
s1.Pop();
cout << s1.Top() << endl;
s1.Pop();
cout << s1.Top() << endl;
s1.Pop();
}