Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

Compile and Execute C Online

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

typedef int ElementType;

typedef struct tagNode
{
    ElementType Data;
} Node;

typedef struct tagArrayStack
{
    int Capacity;
    int Top;
    Node* Nodes;
} ArrayStack;

void AS_CreateStack(ArrayStack** Stack, int Capacity);
void AS_DestroyStack(ArrayStack* Stack);
void AS_Push(ArrayStack* Stack, ElementType Data);
ElementType AS_Pop(ArrayStack* Stack);
ElementType AS_Top(ArrayStack* Stack);
int AS_GetSize(ArrayStack* Stack);
int AS_IsEmpty(ArrayStack* Stack);

void AS_CreateStack(ArrayStack** Stack, int Capacity)
{
    (*Stack)=(ArrayStack*)malloc(sizeof(ArrayStack));
    (*Stack)->Nodes=(Node*)malloc(sizeof(Node)*Capacity);
    (*Stack)->Capacity=Capacity;
    (*Stack)->Top=0;
}

void AS_DestroyStack(ArrayStack* Stack)
{
    free(Stack->Nodes);
    free(Stack);
}

void AS_Push(ArrayStack* Stack, ElementType Data)
{
    int Position = Stack->Top;
    Stack->Nodes[Position].Data = Data;
    Stack->Top++;
}

ElementType AS_Pop(ArrayStack* Stack)
{
    int Position = --(Stack->Top);
    return Stack->Nodes[Position].Data;
}

ElementType AS_Top(ArrayStack* Stack)
{
    int Position = (Stack->Top) - 1;
    return Stack->Nodes[Position].Data;
}

int AS_GetSize(ArrayStack* Stack)
{
    return Stack->Top;
}

int AS_IsEmpty(ArrayStack* Stack)
{
    return (Stack->Top == 0);
}



int main(void)
{
    int i=0;
    ArrayStack* Stack = NULL;
    
    AS_CreateStack(&Stack, 10);
    
    AS_Push(Stack, 3);
    AS_Push(Stack, 37);
    AS_Push(Stack, 11);
    AS_Push(Stack, 12);
    
    printf("Capacity: %d, Size: %d, Top: %d\n\n",Stack->Capacity, AS_GetSize(Stack), AS_Top(Stack));

    while(!AS_IsEmpty(Stack))
    {
        printf("Popped: %d, ",AS_Pop(Stack));
        if(!AS_IsEmpty(Stack))
            printf("Current Top: %d\n",AS_Top(Stack));
    }
    
    printf("Stack Is Empty.\n");
    
    AS_DestroyStack(Stack);

    return 0;
}

Advertisements
Loading...

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.