#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; }