Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- typedef int Container;
- struct Stack{
- int capacity;
- int top;
- Container* stack ;
- };
- struct Stack* buildStack();
- int isEmpty(struct Stack* S);
- void push(int x, struct Stack* S);
- int pop(struct Stack* S);
- int top(struct Stack* S);
- void makeEmpty(struct Stack* S);
- void EmptyTheStackAndPrint(struct Stack* S);
- int main(){
- struct Stack* stack2 = buildStack();
- push(10,stack2);
- push(20,stack2);
- push(30,stack2);
- push(40,stack2);
- push(50,stack2);
- push(60,stack2);
- push(70,stack2);
- push(10,stack2);
- push(20,stack2);
- push(30,stack2);
- push(40,stack2);
- push(50,stack2);
- push(60,stack2);
- push(70,stack2);
- push(10,stack2);
- push(20,stack2);
- push(30,stack2);
- push(40,stack2);
- push(50,stack2);
- push(60,stack2);
- push(70,stack2);
- push(10,stack2);
- push(20,stack2);
- push(30,stack2);
- push(40,stack2);
- push(50,stack2);
- push(60,stack2);
- push(70,stack2);
- EmptyTheStackAndPrint(stack2);
- push(100,stack2);
- push(200,stack2);
- EmptyTheStackAndPrint(stack2);
- return 0;
- }
- struct Stack* buildStack(){
- struct Stack* stk = malloc(sizeof(struct Stack));
- stk->stack = malloc(sizeof(int)*10);
- stk->top = -1;
- stk->capacity = 10;
- return stk;
- }
- int isEmpty(struct Stack* S){
- return S->top == -1;
- }
- void push(int x, struct Stack* S){
- if(S->top+1<S->capacity){
- S->top++;
- int i = S->top;
- S->stack[i] = x;
- }else{
- Container* temp = malloc(sizeof(Container)*S->capacity*2);
- for(int i = 0; i < S->capacity; i++){
- temp[i] = S->stack[i];
- }
- free(S->stack);
- S->stack = temp;
- S->capacity *=2;
- }
- }
- int pop(struct Stack* S){
- if(!isEmpty(S)){
- int i = S->top;
- S->top--;
- return S->stack[i];
- }
- printf("The Stack is empty!\n");
- return -1;
- }
- int top(struct Stack* S){
- if(!isEmpty){
- int i = S->top;
- return S->stack[i];
- }
- printf("The Stack is empty!\n");
- return -1;
- }
- void makeEmpty(struct Stack* S){
- S->top = -1;
- Container* temp1 = malloc(sizeof(int)*10);
- free(S->stack);
- S->stack = temp1;
- S->capacity = 10;
- }
- void EmptyTheStackAndPrint(struct Stack* S){
- while(S->top>-1){
- int x = pop(S);
- printf("%d ",x);
- }
- printf("\n");
- }
Advertisement
Add Comment
Please, Sign In to add comment