由于栈是一种表,因此任何实现表的方法都能实现栈。显然list和vector都支持栈的操作。
栈的链表实现
栈的第一种实现是单链表。我们通过在表的前端插入来实施push
操作,通过删除表前端元素实施pop
操作。top
操作只是考查表前端的元素并返回它的值。有时也把pop
操作和top
操作合二为一。
栈的数组实现
栈的另一种实现避免了链而且可能是更流行的解决方案。它用到来自vector
的back
、push_back
、和pop_back
,因此实现起来很简单。与每个栈相关联的是theArray
和topOfStack
,对于空栈它是-1(这就是空栈初始化的做法)。为将某个元素x推入栈中,我们使topOfStack
增1然后置theArray[topOfStack]=x
。为了弹出栈元素,我们置返回值为theArray[topOfStack]
,然后使topOfStack
减1。
下面给出栈的链表实现:
#ifndef STACK_H
#define STACK_H
template <typename Object>
class SList{
private:
struct Node{
Object data;
Node *next; // 单链表
Node( const Object & d = Object{ }, Node *n = nullptr )
: data(d), next(n) { }
Node ( Object && d, Node *n = nullptr ) : data(d), next(n) { }
};
int theSize;
Node *head;
Node *tail;
public:
void init( )
{
theSize = 0;
head = new Node;
tail = new Node;
head->next = tail;
}
void clear()
{
while (theSize>0) {
pop_front();
}
}
Object front()
{
return head->next->data;
}
Object pop_front( )
{
Node *p = head->next;
Object retVal = p->data;
head->next = p->next;
delete p;
--theSize;
return retVal;
}
void push_front(const Object &x)
{
Node *p = head->next;
head->next = new Node(x, p);
++theSize;
}
int size( )
{
return theSize;
}
SList( ) { init( ); }
SList( const SList& rhs )
{
init();
for(auto x:rhs)
push_back(x);
}
~SList()
{
clear();
}
};
template <typename Object>
class Stack{
private:
SList<Object> SLst;
public:
Stack( ) : SLst() { }
~Stack( ) { }
bool empty( )
{
return SLst.size() == 0;
}
int size( )
{
return SLst.size();
}
void clear( )
{
SLst.clear();
}
void push( const Object &x )
{
SLst.push_front(x);
}
Object pop( )
{
return SLst.pop_front();
}
Object top( )
{
if(SLst.size() == 0)
{
std::cout<<"栈为空!"<<std::endl;
return -1;
}
else
return SLst.front();
}
};
#endif // STACK_H
#include <iostream>
#include "stack.h"
using namespace std;
int main(int argc, char *argv[])
{
Stack<int> s;
for(int i=0; i<10; i++)
{
s.push(i);
}
int num = s.size();
for(int i=0; i<num/2; ++i)
{
cout<<s.pop()<<"\t";
}
cout<<endl<<s.size()<<endl;
int num2 = s.size();
for(int i=0; i<num2; ++i)
{
cout<<s.pop()<<"\t";
}
cout<<endl;
cout<<s.top();
return 0;
}