Last active
October 7, 2016 06:59
-
-
Save priyadarshitathagat/4723ec725055fb3b6218fc2167742ce5 to your computer and use it in GitHub Desktop.
Stack implementation using Linked List in c
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include<stdlib.h> | |
struct node | |
{ | |
int val; | |
struct node *link; | |
}; | |
struct node* getnode( ) | |
{ | |
return ( struct node *)malloc( sizeof( struct node )); | |
}; | |
int c=0,n; | |
struct node* push( struct node *); struct node* pop( struct node *); | |
void display( struct node *); | |
struct node* top; | |
int main() | |
{ | |
struct node *F; | |
int ch; | |
printf("Enter the size in stack: "); | |
scanf("%d",&n); | |
F = NULL; | |
while( 1 ) | |
{ | |
printf("1. To push\n"); | |
printf("2. To pop\n"); | |
printf("3. Display \n"); printf("4. Exit\n"); | |
scanf("%d", &ch ); | |
if( ch == 1 ) | |
F = push (F); | |
else if( ch == 2 ) | |
F = pop (F); | |
else if( ch == 3 ) | |
display(F); | |
else | |
break; | |
} | |
} | |
struct node* push( struct node *FIRST) | |
{ if(c==n) | |
{ | |
printf("Over-flow\n"); return(FIRST); | |
} | |
struct node *T; | |
if( FIRST == NULL ) | |
{ | |
FIRST = getnode(); | |
T =top=FIRST; | |
} | |
else | |
{ | |
T = FIRST; | |
while( T->link != NULL ) T = T->link; | |
T->link = getnode( ); | |
T = T->link; top=T; | |
} | |
printf("Enter the element to push\n"); c++; | |
scanf("%d", &T->val); | |
T->link = NULL; | |
return FIRST; | |
} | |
struct node* pop( struct node *FIRST) | |
{ struct node* T; | |
struct node* P; P=FIRST; | |
if(FIRST==NULL) | |
{printf("stack-underflow\n"); return FIRST;} | |
T=top; | |
printf("The poppped out value is: %d\n",T->val); | |
while(P->link!=NULL) | |
{ T=P; | |
P=P->link; | |
} | |
top=T; top->link=NULL; c--; | |
if(c==0) | |
FIRST=NULL; | |
return FIRST; | |
} | |
void display( struct node *T) | |
{ if(c==0) | |
{ | |
printf("The stack is empty.\n"); return; | |
} | |
printf("The stack contains : \n"); | |
while( T!= NULL ) | |
{ | |
printf("%d ",T->val); | |
T = T->link; | |
} | |
printf("\n"); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment