Tuesday, November 3, 2020

Stack Using Linked List : Code ( C++ )

 

CODE:


// header file

#include<stdio.h>

#include<stdlib.h>


// struct


struct node{

int data;

struct node* next;

};


// operations

//push


void push(struct node ** head , int element){

struct node* p  = (struct node * )malloc(sizeof(struct node));


p->data = element;


//**head -> *head(top of the stack) -> stack


p->next = *head;


*head = p;


}

// isEmpty

int isEmpty(struct node *top){

return top == NULL;

}


// pop

int pop(struct node ** top ){

    if(isEmpty(*top)){

        return -1;

    }else{

        //**head -> *head(top of the stack) -> stack [1 , 2 ,3 ,...]

        //*p = 1

        //*head  = *head->next

        //free(p)


        struct node* p;

        p  = *top;

        *top = (*top)->next;

        int r = p->data;

        free(p);


        return r;


    }

}


// top

int peek(struct node* top){

if(!isEmpty(top)){

    return top->data;

}else{

return -1;

}

}



// main

int main(){


//**q = &*p = &a

struct node* top = NULL;


push(&top,1);

push(&top,2);

push(&top,3);


// 3  2   1


printf("%d",peek(top));


return 0;}








No comments:

Post a Comment