#include <iostream> using namespace std; struct Stack { int top; int capacity; int *array; }; struct Stack *createStack(int capacity){ struct Stack *S=new struct Stack; if(!S) return NULL; S->capacity=capacity; S->top=-1; S->array=new int[capacity]; if (!S->array) return NULL; return S; } int isEmpty(struct Stack *S){ return(S->top==-1); } int size(struct Stack *S){ return(S->top+1); } int isFull(struct Stack *S){ return(S->top==S->capacity-1); } void doubleStack(struct Stack *S){ S->capacity*=2; S->array=realloc(S->array,S->capacity * sizeof(int)); } void push(struct Stack *S,int data){ if (isFull(S)) doubleStack(S); else S->array[++S->top]=data; } int pop(struct Stack *S){ if (isEmpty(S)){ cout<<"Stack is Empty"<<endl; return INT16_MIN; } else return(S->array[S->top--]); } int peek(struct Stack *S){ if (isEmpty(S)){ cout<<"Stack is Empty"<<endl; return INT16_MIN; } else return(S->array[S->top]); } void deleteStack(struct Stack *S){ if (S){ if (S->array){ delete S->array; delete S; } } } int main() { int capacity=5; struct Stack *stack= createStack(capacity); for (int i = 0; i < 2*capacity; ++i) { push(stack,i); } cout<<"top:"<<peek(stack)<<endl; cout<<"size:"<<size(stack)<<endl; for (int i = 0; i < capacity; ++i) { cout<<pop(stack)<<" "; } cout<<endl; if (isEmpty(stack)) cout<<"Stack is Empty"<<endl; else cout<<"Stack is not Empty"<<endl; deleteStack(stack); return 0; }
void doubleStack(struct Stack *S){ S->capacity*=2; S->array=realloc(S->array,S->capacity * sizeof(int)); }
var
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)