栈的顺序存储结构以及实现

 1 #include "stdafx.h"
 2 #include <iostream>
 3 #include <exception>
 4 using namespace std;
 5 
 6 //栈的顺序存储结构及实现
 7 //栈的结构定义
 8 #define OK 1
 9 #define ERROR 0
10 #define TRUE 1
11 #define FALSE 0
12 #define MAXSIZE 5
13 typedef int sElemType;
14 typedef int Status;
15 typedef struct
16 {
17     sElemType data[MAXSIZE];
18     int top;
19 }SqStack;
20 Status Init(SqStack *S)
21 {
22 
23     for(int i = 0;i!=MAXSIZE;++i)
24     {
25         S->data[i]=0;
26     }
27     S->top = -1;
28     return OK;
29 }
30 //压栈操作
31 Status Push(SqStack *S,sElemType e)
32 {
33     if(S->top == MAXSIZE - 1)
34     {
35         cout<<"栈满"<<endl;
36         return ERROR;
37     }
38     S->top++;
39     S->data[S->top]=e;
40     return OK;
41 }
42 //出栈操作
43 Status Pop(SqStack *S,sElemType *e)
44 {
45     if(S->top == -1)
46     {
47         cout<<"栈空"<<endl;
48         return ERROR;
49     }
50     *e = S->data[S->top];
51     (S->top)--;
52     return OK;
53 }
54 //输出栈内元素
55 Status ReadStack(const SqStack *S)
56 {
57     cout<<"栈内元素:";
58     for(int i = 0;i<=S->top;++i)
59     {
60         cout<<S->data[i]<<" ";
61     }
62     cout<<endl;
63     return OK;
64 }
65 
66 int _tmain(int argc, _TCHAR* argv[])
67 {
68     SqStack *stack = (SqStack*)malloc(sizeof(SqStack));
69     Init(stack);//初始化栈
70     Push(stack,1);//将1入栈
71     Push(stack,2);//将2入栈
72     Push(stack,3);//将3入栈
73     Push(stack,4);//将4入栈
74     ReadStack(stack);//输出栈内元素
75     int popElem = 0;
76     Pop(stack,&popElem);//出栈栈顶值赋予popElem
77     cout<<"出栈:"<<popElem<<endl;
78     Pop(stack,&popElem);//出栈栈顶值赋予popElem
79     cout<<"出栈:"<<popElem<<endl;
80     Pop(stack,&popElem);//出栈栈顶值赋予popElem
81     cout<<"出栈:"<<popElem<<endl;
82     ReadStack(stack);//输出栈内元素
83     Pop(stack,&popElem);//出栈栈顶值赋予popElem
84     cout<<"出栈:"<<popElem<<endl;
85     return 0 ;
86 }
原文地址:https://www.cnblogs.com/crazycodehzp/p/3540630.html