栈(stack)是限制插入和删除只能在一个位置上进行的表,该位置是表的末端,叫做栈的顶(top),它是后进先出(LIFO)的。对栈的基本操作只有push(进栈)和pop(出栈)两种,前者相当于插入,后者相当于删除最后的元素。
栈本质上是一种受限制的表,所以可以使用任何一种表的形式来实现它,最常用的是使用链表和数组。
使用链表的特点:不需要指定其大小,不会浪费空间;进栈和出栈涉及到动态内存的申请释放,时间花销大;
使用数组的特点:需要指定其大小,有可能浪费空间,也可能空间不够用;进栈和出栈不涉及动态内存的申请释放,因此时间上几乎没有花销;另外支持随机存取。
结论:一般使用链表是首选,除非满足两个条件:1.对运行时的效率要求极高;2.能够预知栈需要的空间大小。
数组实现栈:
#include<iostream>
using namespace std;
class stack
{
private:
int data[100];
int top;
public:
stack();
bool isempty();
bool isfull();
void push(int n);
void pop();
void gettop();
};
stack::stack()
{
top=-1;
}
bool stack::isempty()
{
return top==-1?true:false;
}
bool stack::isfull()
{
return top==99?true:false;
}
void stack::push(int n)
{
if(!isfull())
{
++top;
data[top]=n;
}
else
cout<<"栈溢出"<<endl;
}
void stack::pop()
{
if(!isempty())
{
cout<<"出栈元素"<<endl;
cout<<data[top]<<endl;
top--;
}
else
cout<<"栈为空"<<endl;
}
void stack:: gettop()
{
if(!isempty())
{
cout<<"栈顶元素"<<endl;
cout<< data[top]<<endl;
}
else
cout<<"栈为空"<<endl;
}
int main()
{
stack s;
s.push(6);
s.push(8);
s.push(9);
s.push(18);
s.push(88);
s.push(99);
s.gettop();
s.pop();
s.gettop();
s.pop();
s.gettop();
return 0;
}
链表实现栈:
#include<iostream>
using namespace std;
struct node
{
int data;
node* next;
};
class stack
{
private:
node* head;
public:
stack();
void push(int item);
int pop();
void display();
~stack();
};
stack::stack()
{
head=new node;
head->next=NULL;
}
void stack:: push(int item)
{
node *p,*q;
q=head;
p=new node;
p->data=item;
p->next=NULL;
while(NULL!=q->next)
q=q->next;
q->next=p;
}
int stack::pop()
{
node *p,*q;
int aa;
p=head;
if(NULL==p->next)
{
cout<<"这是最后一个元素"<<endl;
}
else
{
while(p->next->next)
p=p->next;
}
q=p->next;
aa=q->data;
p->next=NULL;
delete q;
q=NULL;
return aa;
}
void stack::display()
{
node*p=head;
while(p->next)
{
cout<<p->next->data;
p=p->next;
cout<<" ";
}
cout<<endl;
}
stack::~stack()
{
node *p;
while(head->next)
{
p=head;
head=head->next;
delete p;
p=NULL;
}
delete head;
head=NULL;
}
int main()
{
stack s;
s.push(10);
s.push(12);
s.push(14);
cout<<"存入栈里面的元素"<<endl;
s.display ();
cout<<s.pop()<<endl;
cout<<s.pop()<<endl;
return 0;
}