顺序栈的实现 C语言/C++
基本数据结构实现--顺序栈
顺序栈是栈的顺序存储方式实现。栈的大小不可改变。可以用以下结构定义一个顺序栈:
1 typedef struct SNode { 2 ElemType data[MaxSize]; //存放栈中的元素 3 int top; //栈顶元素在数组中的下标 4 }SqStack;
*栈的基本操作
(1) 初始化一个栈
事实上,栈顶指针可以指向栈顶元素,也可以指向栈顶元素的下一个位置,二者只是在入栈出栈等操作上略有不同。本文以栈顶指针指向栈顶元素为例,实现一个顺序栈。
将栈顶指针top置为-1,即在逻辑上初始化了一个栈。
(2) 判空
1 bool StackEmpty(SqStack S) 2 { 3 if( S.top == -1 ) 4 return true; 5 return false; 6 }
(3) 进栈操作
1 bool Push( SqStack& S,ElemType x ) 2 { 3 if( S.top == MaxSize - 1 ) //栈满 4 return false; 5 S.data[++S.top] = x; 6 return true; 7 }
先将栈顶指针后移一位,再将元素送到栈顶。
(4) 出栈操作
1 bool Pop( SqStack& S,ElemType& x ) 2 { 3 if( S.top == -1 ) 4 return false; 5 x = S.data[S.top--]; 6 return true; 7 }
先送栈顶元素出栈,再将栈顶指针前移一位。
*代码测试
1 /* 顺序栈 2 3 实现操作: 4 *1 判空 5 *2 入栈 6 *3 出栈 7 *4 读栈顶元素(栈顶元素依然保留) 8 9 */ 10 #include <iostream> 11 #include <cstdio> 12 using namespace std; 13 14 typedef int ElemType; 15 const int MaxSize = 10; 16 17 typedef struct SNode { 18 ElemType data[MaxSize]; //存放栈中的元素 19 int top; //栈顶元素在数组中的下标 20 }SqStack; 21 22 //初始化一个顺序栈 23 void InitStack(SqStack& S) 24 { 25 S.top = -1; 26 } 27 28 //判空 29 bool StackEmpty(SqStack S) 30 { 31 if( S.top == -1 ) 32 return true; 33 return false; 34 } 35 36 //进栈操作:将x压入堆栈 37 bool Push( SqStack& S,ElemType x ) 38 { 39 if( S.top == MaxSize - 1 ) //栈满 40 return false; 41 S.data[++S.top] = x; 42 return true; 43 } 44 45 //出栈操作:将栈顶元素出栈,并用x返回 46 bool Pop( SqStack& S,ElemType& x ) 47 { 48 if( S.top == -1 ) 49 return false; 50 x = S.data[S.top--]; 51 return true; 52 } 53 54 //读栈顶元素 55 bool GetTop( SqStack S,ElemType& x ) 56 { 57 if( S.top == -1 ) 58 return false; 59 x = S.data[x]; 60 return true; 61 } 62 63 void test1() 64 { 65 SqStack S; 66 InitStack(S); 67 for( int i=1; i<=11; i++ ) { 68 if( Push(S,i) ) { 69 cout << "入栈成功,入栈的元素是:" << i << endl; 70 } 71 else 72 cout << "栈满,入栈失败" << endl; 73 } 74 cout << "-----------------------" << endl; 75 while( !StackEmpty(S) ) { 76 int e ; 77 Pop(S,e); 78 cout << e << endl; 79 } 80 81 } 82 83 int main() 84 { 85 test1(); 86 return 0; 87 }
上一篇【双链表的实现C/C++】:https://www.cnblogs.com/pkuqcy/p/14951810.html
下一篇【堆栈的链式存储实现C/C++】:https://www.cnblogs.com/pkuqcy/p/14985763.html