栈的两种C++实现

本文详细介绍了栈数据结构的链表和数组实现方式,包括各自的优缺点及使用场景。通过实例代码展示了如何在实际应用中运用这些实现。

栈(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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值