顺序栈的实现。。。。


///ADTstack///
//                     data 相邻元素具有前驱和后继关系
//                     operation
//                     InitStack(*S) 初始化操作,建立一个空栈
//                     DestroyStack(*S)若栈存在,则销毁它
//                     ClearStack(*S) 将栈清空
//                     StackEmpty(*S) 若栈为空 返回true 否则返回false
//                     GetTop(S, *e) 若为非空则返回栈顶元素e
//                     Push(*S, e) 将元素e压入栈中
//                     Pop(*S, e)将元素出栈 并返回其值
//                     StackLength(S) 返回栈S元素个数
//
///endADT/
//                     data 2012 12 20 by oujiayao 
//


# include <iostream>
# define MAXSIZE 20


using namespace std;


typedef struct
{
int data[MAXSIZE];
int top; //栈顶指针
}SqStack;


void InitStack(SqStack *S)
{
S->top = -1;
}


bool StackEmpty(SqStack *S)
{
if(S->top == -1)
return true;
else
return false;


}


void Push(SqStack *S, int a, int b, int c, int d, int e)
{
if(S->top == MAXSIZE-1) //栈满不能入栈
{
exit(0);
}
else
{
S->top++;  //这样栈指针才能指向0
S->data[S->top] = a;

S->top++;
S->data[S->top] = b;

S->top++;
S->data[S->top] = c;

S->top++;
S->data[S->top] = d;

S->top++;
S->data[S->top] = e;

}




}


void Pop(SqStack *S)
{
int elem;


if(S->top == -1)
{
exit(0);
}
else
{
elem = S->data[S->top];
S->top--;
}
}
void printStack(SqStack *S)
{
int i;


cout << "\n\n栈表的输出:" << endl;

for(i=S->top; i>=0; i--)
cout << S->data[i] << endl;


}


int GetTop(SqStack S)
{
return S.data[S.top];
}


int StackLength(SqStack S)
{
int count=0, j;
for(j=S.top; j>=0; j--)
count++;


return count;
}


int main(void)
{
SqStack S;


cout << "初始化一个空栈:" << endl;
InitStack(&S);

if(!StackEmpty(&S))
{
cout << "栈是空的!" << endl;
}
else
{
cout << "压入5个数据:";
Push(&S, 1, 2, 3, 4, 5);
printStack(&S);


cout<< "\n\n栈顶元素是:" << GetTop(S);


cout<< "\n\n栈的长度是:" << StackLength(S) << endl;
}

cout << "\n\n出栈的第一个元素并显示:";


Pop(&S);
printStack(&S);




return 0;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值