顺序栈的建立

#include <iostream>
#include <cstring>
#include <cstdio>
#include <ctime>
#include <cstdlib>
using namespace std;

#define MAX 100
typedef int ElemType;

typedef struct Stack
{
	ElemType elem[MAX];
	int top;
}Stack;

void InitStack(Stack *S)//顺序栈初始化
{
	S->top = -1;
	memset(S->elem, 0, sizeof(S->elem));
}

int Push(Stack **S, ElemType e)
{
	if((*S)->top == MAX - 1)
	{
		return false;
	}
	(*S)->top++;
	(*S)->elem[(*S)->top] = e;
	return true;
}


int Pop(Stack *S, ElemType *x)
{
	if(S->top == -1)
	{
		return false;
	}
	*x = S->elem[S->top];
	S->top--;
	return true;
}

int GetTop(Stack *S, ElemType *x)
{
	if(S->top == -1)
	{
		return false;
	}
	*x = S->elem[S->top];
	return true;
}

void Rand(Stack *S, int length)
{
	//S->top = length - 1;
	for(int i = 0; i <= length - 1; i++)
	{
		//S->elem[i] = rand() % 100;
		Push(&S, rand() % 100);
	}

}

void Show(Stack *S)
{
	for(int i = S->top; i >= 0; i--)
	{
		cout << S->elem[i] << " ";
	}
	cout << endl;
}

int main()
{
	srand((unsigned)time(NULL));
	Stack S;
	ElemType e;
	InitStack(&S);
	int length = rand() % 10;
	cout << "一共" << length << "个元素" << endl;
	Rand(&S, length);
	cout << "元素输出" << endl;
	Show(&S);
	while(S.top != -1)
	{
		GetTop(&S, &e);
		cout << e << " ";
		Pop(&S, &e);
	}
	cout << endl;
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值