堆栈的顺序存储实现

 1 #define MaxSize <储存数据元素的最大个数>
 2 
 3 typedef struct SNode *Stack;
 4 
 5 struct SNode {
 6 
 7   ElementType Data[MaxSize];
 8 
 9   int Top;  //栈顶的位置数组下标
10 
11 }

(1)入栈

 1 void Push (Stack PtrS, ElementType item){
 2 
 3   if (PtrS->Top == MaxSize-1) {
 4 
 5     printf("堆栈满");  return;
 6 
 7   }
 8 
 9   else {
10 
11     PtrS->Data[++(PtrS->Top)] = item;
12     //(PtrS->Top)++  PtrS->Data[PtrS->Top] = item;
13     return;
14 
15   }
16 
17 }

(2)出栈

 1 ElementType Pop (Stack PtrS) {
 2 
 3   if (PtrS->Top == -1) {
 4 
 5     printf("堆栈空");
 6 
 7     return ERROR;  
 8 
 9     //ERROR是ElementType的特殊值,标志错误
10 
11   }
12 
13   else {
14 
15     return (PtrS->Data[(PrtS->Top)--]);
16 
17   }
18 
19 }

一个数组实现两个堆栈

 1 #define MaxSize <储存数据元素的最大个数>
 2   
 3   typedef struct SNode *Stack;
 4   
 5   struct DStack {
 6   
 7      ElementType Data[MaxSize];
 8     int Top1;  //堆栈1的栈顶指针
 9     int Top2;  //堆栈2的栈顶指针
10  
11 } S;
12 S.Top1 = -1;
13 S.Top2 = MaxSize;

创建堆栈

1 Stack CreateStack( int MaxSize ){
2     Stack s = (Stack)malloc(sizeof(struct SNode));  //创造空间
3     s->Data = (int*)malloc(MaxSize*sizeof(int));    //创造大小为MaxSize的数组
4     s->Top1 = -1;   //设置边界
5     s->Top2 = MaxSize;
6     s->MaxSize = MaxSize;
7     return s;
8 }

分别入栈

 1 void Push (struct Dstack *PtrS, ElementType item, int Tag) {
 2 
 3   //Tag作为区分两个堆栈的标志,取值为1和2
 4 
 5   if (PtrS->Top2 - PtrS->Top1 == 1) {
 6 
 7     printf("堆栈满");  return;
 8 
 9   }
10 
11   if (Tag == 1)   //对第一个堆栈操作
12 
13     PtrS->Data[++(PtrS->Top1)] = item;
14 
15   else 
16 
17     PtrS->Data[--(PtrS->Top2)] = item;
18 
19 }

出栈

 1 ElementType Pop ( struct DStack *PtrS, int Tag ){
 2 
 3   if (Tag == 1) {
 4 
 5     if (PtrS->Top1 == -1) {
 6 
 7       printf("堆栈1空");  return NULL;
 8 
 9     }
10 
11     else {
12 
13       return PtrS->Data[(PtrS->Top1)--];
14 
15     }
16 
17   else {
18 
19     if (PtrS->Top1 == MaxSize) {
20 
21       printf("堆栈2空");  return NULL;
22 
23     }
24 
25     else {
26 
27       return PtrS->Data[(PtrS->Top2)++];
28 
29     }
30 
31   }
32 
33 }
原文地址:https://www.cnblogs.com/zhengxin909/p/12526975.html