大连建站费用/邢台网站网页设计
堆栈的顺序存储
- 1.结构体定义
- 2.入栈
- 3.出栈
- 4.初始化
- 5.判断是否为空
- 5.判断是否已满
- 6.输出当前所有元素
- 7.测试代码
- 8.全部代码
1.结构体定义
顺序存储通常由一个一维数组和记录栈顶元素位置的变量构成。
#define MaxSize 100//<存储数据元素的最大个数>
typedef int ElementType;typedef struct SNode*Stack;
struct SNode
{ElementType Data[MaxSize]; //一维数组int Top; //记录栈顶元素位置
};
Stack PtrS;
2.入栈
- 入栈返回void,出栈返回ElementType (当前元素)
void Push(Stack PtrS,ElementType item)
{if(PtrS->Top ==MaxSize-1) //先检查堆栈是否满了{printf("堆栈满");return ;}else{PtrS->Data[++(PtrS->Top)] = item;return;}
}
3.出栈
ElementType Pop(Stack PtrS)
{if(PtrS->Top == -1) //先检查堆栈是否为空{printf("堆栈空,不可出栈\n");return ERROR; //标志错误}else{// 返回当前top的值,top再减一return PtrS->Data[(PtrS->Top)--] ;}
}
4.初始化
Stack CreateStack()
{PtrS = (Stack)malloc(sizeof(struct SNode));PtrS->Top = -1;return PtrS;
}
5.判断是否为空
int IsEmpty(Stack PtrS)
{return (PtrS->Top==-1);
}
5.判断是否已满
int IsEmpty(Stack PtrS)
{return (PtrS->Top==-1);
}
6.输出当前所有元素
void print(Stack PtrS)
{if(IsEmpty(PtrS)){printf("当前堆栈为空\n");return;}printf("当前存储: ");int temp = PtrS->Top;while(temp!=-1){printf("%d ",PtrS->Data[temp]);temp--;}printf("\n");
}
7.测试代码
PtrS = CreateStack();printf("堆栈空? %d (1表示空,0表示满)\n",IsEmpty(PtrS));//print(PtrS);Pop(PtrS);printf("入栈:5\n");Push(PtrS,5);print(PtrS);printf("入栈:3\n");Push(PtrS,3);print(PtrS);printf("入栈:1\n");Push(PtrS,1);print(PtrS);Push(PtrS,1);printf("堆栈满? %d (1表示满,0表示空)\n",IsFull(PtrS));printf("出栈:\n");Pop(PtrS);print(PtrS);
8.全部代码
#include<stdlib.h>
#include<stdio.h>
#define ERROR -1
#define MaxSize 3//<存储数据元素的最大个数>
typedef int ElementType;typedef struct SNode*Stack;
struct SNode
{ElementType Data[MaxSize];int Top;
};
Stack PtrS;//初始化
Stack CreateStack()
{PtrS = (Stack)malloc(sizeof(struct SNode));PtrS->Top = -1;return PtrS;
}//入栈
void Push(Stack PtrS,ElementType item)
{if(PtrS->Top == MaxSize-1) //先检查堆栈是否满了{printf("堆栈满");return ;}else{PtrS->Data[++(PtrS->Top)] = item;return;}
}
//出栈
ElementType Pop(Stack PtrS)
{if(PtrS->Top == -1) //先检查堆栈是否为空{printf("堆栈空,不可出栈\n");return ERROR; //标志错误}else{// 返回当前top的值,top再减一return PtrS->Data[(PtrS->Top)--] ;}
}int IsFull(Stack PtrS)
{return (PtrS->Top==MaxSize-1);}int IsEmpty(Stack PtrS)
{return (PtrS->Top==-1);}//输出当前所有元素
void print(Stack PtrS)
{if(IsEmpty(PtrS)){printf("当前堆栈为空\n");return;}printf("当前存储: ");int temp = PtrS->Top;while(temp!=-1){printf("%d ",PtrS->Data[temp]);temp--;}printf("\n");
}int main()
{PtrS = CreateStack();printf("堆栈空? %d (1表示空,0表示满)\n",IsEmpty(PtrS));//print(PtrS);Pop(PtrS);printf("入栈:5\n");Push(PtrS,5);print(PtrS);printf("入栈:3\n");Push(PtrS,3);print(PtrS);printf("入栈:1\n");Push(PtrS,1);print(PtrS);Push(PtrS,1);printf("堆栈满? %d (1表示满,0表示空)\n",IsFull(PtrS));printf("出栈:\n");Pop(PtrS);print(PtrS);system("pause");return 0;
}