Search
 
SCRIPT & CODE EXAMPLE
 

C

dynamic stack in c

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

typedef struct
{
    int *ptr;
    int tos;
    int size;
} stack;

void push(stack *sp, int data)
{
    if(sp->tos == sp->size -1)
    {
        // creating stack of double the size in case the stack is full and data needs to be stacked.
        int*new_ptr = (int*)malloc(sizeof(int)*sp->size*2);
        // copying the data into the new stack
        for(int i=0; i<sp->size; i++)
        {
            new_ptr[i] = sp->ptr[i];
        }
        // deallocating the memory occupied by the previous stack that was full
        free(sp->ptr);
        // stack pointer pointing to the newly allocated double memory stack
        sp->ptr = new_ptr;
        sp->size *=2;
    }
    else
    {
        sp->tos ++;
        sp->ptr[sp->tos] = data;
    }
}

int pop(stack *sp)
{
    if(sp->ptr[sp->tos] == -1)
        printf("Stack is empty");
    int data = sp->ptr[sp->tos];
    sp->tos --;
    return data;
}

int peek(stack *sp)
{
    if(sp->ptr[sp->tos]= -1)
        printf("Stack is empty");
    else
    {
        int data = sp->ptr[sp->tos];
        return data;
    }
}

// creating size of stack
stack * create(int size)
{
    stack *sp = (stack*)malloc(sizeof(stack));
    sp->ptr = (int*) malloc(sizeof(int)*size);
    sp->tos = -1;
    sp->size = size;
}

int main()
{
    stack *sp = create(5);
    push(sp, 1);
    push(sp, 2);
    push(sp, 3);
    push(sp, 4);
    push(sp, 5);

    printf("Stack Size : %d
--------------
",sp->size);
    printf(" _____
");
    while(sp->tos > -1)
    {
        printf("|__%d__| 
",pop(sp));
    }
}
Comment

PREVIOUS NEXT
Code Example
C :: c logarithm check if number is base 
C :: sdl_rect 
C :: countoddevenDifference 
C :: scanf autotrash c 
C :: increase size of array in c 
C :: c declare float 
C :: C Syntax of function prototype 
C :: merge sort in c 
C :: Happy New Year! 
C :: arrays c 
C :: arduino analogwrite 
Dart :: flutter remove debug flag 
Dart :: asset image in circle avatar flutter 
Dart :: rel canonical tag 
Dart :: flutter border around textbutton 
Dart :: switch to another flutter channel eg. $ flutter channel beta $ flutter channel stable 
Dart :: flutter appbar trailing icon 
Dart :: flutter textfield with icon onclick 
Dart :: flutter absorbpointer 
Dart :: The build failed likely due to AndroidX incompatibilities in a plugin. The tool is about to try 
Dart :: flutter floatingactionbutton position 
Dart :: type convertion string to double 
Dart :: underscore dart 
Dart :: flutter style diabled button 
Dart :: how to subtract dates in flutter 
Dart :: switch case dart 
Dart :: sort list bool dart 
Dart :: flutter get operating system 
Dart :: double to animation in flutter 
Dart :: open url in flutter 
ADD CONTENT
Topic
Content
Source link
Name
4+6 =