C program for linked list implementation of stack

C program for linked list implementation of stack
Push: Adds an item in the stack. If the stack is full, then it is said to be an Overflow condition.

Pop: Removes an item from the stack. The items are popped in the reversed order in which they are pushed. If the stack is empty, then it is said to be an Underflow condition

#include<stdio.h>
#include<stdlib.h>
#define MAX_SIZE 100

struct node{

int data;
struct node *next;
};
struct node *Top=NULL;


void push(int n)
{
struct node *new_node=(struct node*)malloc(sizeof(struct node));

new_node->data=n;
new_node->next=Top;
Top=new_node;

}

void pop()
{
struct node *temp;
if(Top==NULL)
return;

temp=Top;
Top=Top->next;
free(temp);

}

void print(struct node *Top)  //traverse linked list from Top and print

{
int i;
struct node *x;
x=Top;

printf("Stack is:\t");

while(x!=0)
{
printf("%d\t",x->data);
x=x->next;
}
printf("\n\n");
}

main()
{
//push element into stack
push(1);
print(Top);
push(2);
print(Top);
push(3);
print(Top);
push(4);
print(Top);
push(5);
print(Top);

//pop element from stack
pop();
print(Top);
pop();
print(Top);
pop();
print(Top);
pop();
print(Top);
pop();
print(Top);

}

Related Posts