stack using linked list

Last Updated on

stack is a type of data structure.this is LIFO (Last In First Out) type of data stures.in the stack, elements can be added or removed only from one end

the advantage of stacks using linked list is , there is size limit ,we can insert and deleted n number of elements

we need to define node structure first

struct node
{
   int data;
   struct node *next;
}*top = NULL;

create a top pointer for that node structure, assign NULL to the top pointer

push elements into stack

create a newnode pointer fro the structure node,use malloc to allocate data, assign value from the user to newnode->data

if (top==NULL) ,then the inserted element will be first element, so assign top pointer to the newnode and make newnode next next address to NULL

top=newnode
newNode->next = NULL

else,for the next elements, link next address of newnode to the top element,and point top to the current newnode ,so now newnode becomes top element

Node->next = top
top = newNode

pop elements into stack

if (top=NULL) display “StackOverflow”

create a temp pointer and initialise top pointer to temp pointer,in stacks top element will be deleted, display (temp->data) data from temp pointer and move top pointer to temp->next , now top points to the second element

top = temp->next;

free temp pointed element (free(temp))