数据结构--堆栈的范例程序

堆栈本身可以使用静态数组结构或动态链表结构实现,只要维持堆栈后进先出和从顶端读取数据两个基本原则即可。利用数据结构来实现堆栈的好处是算法设计简单,下面将用队列来模拟堆栈。范例是:以数组模拟扑克牌的洗牌及发牌过程,以点数取得扑克牌后放入堆栈,放满52张牌后利用堆栈功能来给4个人发牌。

#include<iostream>
#include<iomanip>
#include<ctime>
#include<cstdlib>
using namespace std;
void Swap(int *,int *);
void push(int statck[],int MAX,int val);
int pop(int stack[]);
int top=-1;
int main()
{
int card[52]={0},stack[52]={0};
int i,j,k=0;
char ascVal;
int style;
srand((unsigned)time(NULL));
for(i=0;i<52;i++)
card[i]=i+1;
cout<<"[洗牌中,请稍候!]"<<endl;
while(k<30)   //洗牌
{
for(i=0;i<51;i++)
for(j=i+1;j<52;j++)
if(rand()%52==2)
Swap(&card[i],&card[j]);//传递的地址值可以直接交换数组的数据
k++;
}
i=0;
while(i!=52)
{
push(stack,52,card[i]);  //将52张牌放入堆栈
i++;
}
cout<<"[逆时针发牌]"<<endl;
cout<<"[显示各家牌面]"<<endl;
cout<<"东家\t北家\t西家\t南家"<<endl;
cout<<"============================"<<endl;
while(top>=0)
{
style = stack[top]/13;  //计算牌面花色
switch(style)     //牌面花色对应显示
{
case 0:    //梅花
ascVal=5;
break;
case 1:   //方块
        ascVal =4;
break;
case 2:  //红桃
ascVal=3;
break;
case 3:   //黑桃
ascVal=6;
break;
}
cout<<"["<<ascVal<<setw(3)<<stack[top]%13+1<<"]\t";
if(top%4==0)  //输出四个元素后换行
cout<<endl;
top--;
}
system("pause");
return 0;
}
void push(int stack[],int MAX,int val)
{
if(top>=MAX-1)
cout<<"[堆栈已经满了]"<<endl;
else
{
top++;
stack[top]=val;
}
}
int pop(int stack[])
{
if(top<0)
cout<<"[堆栈已经空了]"<<endl;
else
top--;
return stack[top];
}
void Swap(int *a,int *b)
{
int temp;
temp=*a;
*a=*b;
*b=temp;
}

虽然以数组结构来实现堆栈的好处是算法设计简单,但如果堆栈的大小可以改变的话,由于数组的大小需要事先声明,这时必须使用最大可能性的数组空间来考虑堆栈,这样会造成内存空间的浪费。而利用链表来实现堆栈的优点是可以随时动态改变链表的长度,不过缺点是设计时算法较为复杂。下面用链表模拟堆栈。



#include<iostream>
#include<cstdlib>
#include<iomanip>
using namespace std;
class Node
{
public:
int data;   //堆栈数据的声明
class Node *next; //堆栈中用来指向下一个结点
};
typedef class Node Stack_Node;//定义堆栈中结点的新类型
typedef Stack_Node *Linked_Stack;//定义链表堆栈的新类型
Linked_Stack top=NULL;//指向堆栈顶端的指针
//判断是否为空堆栈
int isEmpty()
{
if(top==NULL) return 1;
else return 0;
}
//将指定的数据存入堆栈
void push(int data)
{
Linked_Stack new_add_node;//新加入结点的指针
new_add_node=new Stack_Node;
new_add_node->data=data;//将新传入的值指定为结点的内容
new_add_node->next=top;//将新结点指向堆栈的顶端
top=new_add_node;//新结点成为堆栈的顶端
}
//从堆栈中取出数据
int pop()
{
Linked_Stack ptr;//指向堆栈顶端的指针
int temp;
if(isEmpty())//判断堆栈是否为空,是则返回-1
{
cout<<"==目前为空栈"<<endl;
return -1;
}
else
{
ptr=top;//指向堆栈的顶端
top=top->next;//将堆栈顶端的指针指向下一个结点
temp=ptr->data;//取出堆栈的数据
free(ptr);//将结点占用的内存空间释放
return temp;//将从堆栈中取出的数据返回给主程序
}
}


int main(void)
{
int value;
int i;
cout<<"请依次输入十个数据:"<<endl;
for(i=0;i<10;i++)
{
cin>>value;
push(value);
}
cout<<"======================"<<endl;
while(!isEmpty())//将数据陆续从顶端弹出
cout<<"堆栈弹出的顺序为:"<<setw(3)<<pop()<<endl;
cout<<"======================"<<endl;
system("pause");
return 0;
}








评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值