F How to Implement a Stack using single link list in C? | CodeTheta

How to Implement a Stack using single link list in C?

April 17, 2014

This is a single link list programming which is implemented by stack. Here you can see the malloc function which is used to create the memory dynamically or runtime. After the stack creation the push and pop method will apply to this stack.

/* http://native-code.blogspot.com */

#include<stdio.h>
#include<conio.h>
#include<malloc.h>
typedef struct link
{
int data;
struct link *next;
} node;
node *top=NULL;
void push(int);
int pop();
void display();
void main()
{
int ch,k,p;
while(1)
{
printf("/* http://native-code.blogspot.com */");
printf("\n\n1: Push\n2: Pop\n3: Display\n4: EXIT\n");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("Enter element to push:\n");
scanf("%d",&k);
push(k);
break;
case 2:
if(top==NULL)
printf("Stack underflow\n");
else
{
p=pop();
printf("Popped number is: %d\n",p);
}
break;
case 3:
display();
printf("\n");
break;
case 4:
exit(0);
default:
printf("Wrong choice.\n");
}
}
}
void display()
{
node* p = top;
while(p!=NULL)
{
printf("%d-->",p->data);
p=p->next;
}
printf("NULL");
}
void push(int k)
{
node *temp;
temp=(node*) malloc (sizeof(node));
temp->data=k;
temp->next=NULL;
if(top==NULL)
top=temp;
else
{
temp->next=top;
top=temp;
}
}
int pop()
{
int tmp;
tmp=top->data;
top=top->next;
return(tmp);
}

/* http://native-code.blogspot.com */
Try this code in your computer for better understanding. Enjoy the code. If you have any Question you can contact us or mail us

Post a Comment