Stack is another linear data structure in addition to linear table. The name "stack" vividly represents the characteristics of this data structure. It can only operate at one end of the data, that is, it can only realize "in stack" and "out stack" at the top of the stack. And the way that sequential stack opens up memory space is similar to that of sequential table, and the implementation of sequential stack is relatively simple. The operation of this implementation includes:
- Construct empty stack
- Push
- Stack out
- Print every element from the bottom to the top of the stack
#include<stdio.h> #include<stdlib.h> #include "malloc.h" #define TRUE 1 #define FALSE 0 #define OK 1 #define ERROR 0 #define INFEASIBLE -1 #define OVERFLOW -2 #define STACK_INIT_SIZE 5 #define STACKINCREMENT 10 typedef int Status; typedef struct{ int *top; //Top pointer of stack int *base; //Bottom pointer int stacksize; }SqStack; Status InitStack_Sq(SqStack &S){ //Construct empty stack S.base = (int *)malloc(STACK_INIT_SIZE * sizeof(int)); if(!S.base)exit (OVERFLOW); S.top = S.base; S.stacksize = STACK_INIT_SIZE; return OK; } Status Push(SqStack &S,int e){ //e stack if(S.top - S.base >= S.stacksize){ S.base = (int *)realloc(S.base,(S.stacksize + STACKINCREMENT) * sizeof(int)); if(!S.base)exit(OVERFLOW); S.top = S.base + S.stacksize; S.stacksize += STACKINCREMENT; } *S.top++ = e; return OK; } Status GetTop(SqStack S,int &e){ //Get stack top element if (S.top == S.base)return ERROR; e = *(--S.top); printf("Stack top element:%d\n",e); return OK; } Status Pop(SqStack &S,int &e){ //Delete the top element of the stack and use e to return (out of the stack) if(S.top == S.base)return ERROR; e = *(--S.top); printf("%d Deleted\n",e); return OK; } Status print_sq(SqStack S){ //Print each element in turn from the bottom to the top of the stack printf("The elements from the bottom to the top of the stack are:\n"); for(int j = 0;j < (S.top - S.base);j++)printf("%d ",*(S.base + j)); printf("\n"); return OK; } int main() { SqStack S; int e; int count, i; InitStack_Sq(S); printf("Please enter the number of elements to stack: N = "); scanf("%d", &count); printf("Please enter the element:"); for (i = 0; i < count; i++) { scanf("%d", &e); Push(S, e); } print_sq(S); GetTop(S,e); printf("Please enter the element to insert the stack: "); scanf("%d", &e); Push(S, e); GetTop(S,e); print_sq(S); printf("\n Demonstrate stack operation\n"); Pop(S,e); print_sq(S); GetTop(S,e); return 0; }
The compiler used is dev c + +