Sunday, June 28, 2015

Dynamic Implementation of Stack

Posted By: BackBenchers World - Sunday, June 28, 2015

Share

& Comment

#include<stdio.h>
#include<conio.h>
#include<alloc.h>

struct node
{
int info;
struct node *link;
}*top;

void create()
{
struct node *ptr, *cpt;
char ch;

ptr=(struct node*)malloc(sizeof(struct node));    //Allocating memory to ptr

printf("Enter the information of first node: ");
scanf("%d",&ptr->info);

ptr->link=NULL;

do
{
cpt=(struct node*)malloc(sizeof(struct node));    //Allocating memory to cpt

printf("\nEnter the information of next node: ");
scanf("%d",&(cpt->info));

cpt->link=ptr;
ptr=cpt;

printf("\nPress <Y> for more nodes\n");
ch=getch();
}
while(ch=='y'||ch=='Y');
top=ptr;
}

void traverse()
{
struct node *ptr;
ptr=top;

if(ptr==NULL) printf("Stack Underflow");

else
{
printf("\nThe Elements in the list are: ");
while(ptr!=NULL)
{
printf("\n%d",ptr->info);
ptr=ptr->link;
}
}
}

pop()
{
struct node *ptr;

if(top==NULL)
{
printf("Stack Underflow");
}

else
{
ptr=top;
top=ptr->link;
free(ptr);
traverse();
}
}

push()
{
struct node *ptr, *cpt;

ptr=(struct node*)malloc(sizeof(struct node));    //Allocating memory to ptr

printf("Enter the information of node: ");
scanf("%d",&ptr->info);

ptr->link=top;
top=ptr;
traverse();
}

void main()
{
clrscr();
char ch=1;
char choice;
printf("Working with Data Strucrure\n\n");
printf("Menu\n\n1. Create\n2. Push\n3. Pop\n4. Traverse\n");
printf("0. Exit");

while(ch)
{
printf("\n\nEnter your choice: \n");
choice=getch();

switch(choice)
{
case '1': create();
break;

case '2': push();
break;

case '3': pop();
break;

case '4': traverse();
break;

case '0': return;

default: printf("Wrong choice");
}
}
}

About BackBenchers World

Techism is an online Publication that complies Bizarre, Odd, Strange, Out of box facts about the stuff going around in the world which you may find hard to believe and understand. The Main Purpose of this site is to bring reality with a taste of entertainment

0 comments:

Post a Comment

Copyright © 2013 TechDotHunter™ is a registered trademark.

Designed by Templateism. Hosted on Blogger Platform.