Create a stack to store number and use it to reverse an integer - C Data Structure

C examples for Data Structure:Stack

Description

Create a stack to store number and use it to reverse an integer

Demo Code

#include <stdio.h>
#include <stdlib.h>

#define Error -9999// w w  w .j a  va2  s  .c  o m
#define MaxStack 10

typedef struct {
    int top;
    int ST[MaxStack];
} StackType, *Stack;

Stack initStack();
int empty(Stack);
void push(Stack, int);
int pop(Stack);


int main() {
    int n;
    Stack S = initStack();
    
    printf("Enter some integers, ending with 0\n");
    
    scanf("%d", &n);
    
    while (n != 0) {
        push(S, n);
        scanf("%d", &n);
    }
    printf("Numbers in reverse order\n");
    
    while (!empty(S))
        printf("%d ", pop(S));
}

Stack initStack() {
    Stack sp = (Stack) malloc(sizeof(StackType));
    sp -> top = -1;
    return sp;
}

int empty(Stack S) {
    return (S -> top == -1);
}

void push(Stack S, int n) {
    if (S -> top == MaxStack - 1) {
        printf("\nStack Overflow\n");
        exit(1);
    }
    ++(S -> top);
    S -> ST[S -> top]= n;
}

int pop(Stack S) {
    if (empty(S)) 
       return Error;
    int hold = S -> ST[S -> top];
    --(S -> top);
    return hold;
}

Related Tutorials