#include <stdio.h>
#include <stdlib.h>
struct tag
{
int data;
struct tag *link;
};
typedef struct tag * NODE;
void push_node();
void pop_node();
void display();
int main()
{
int ch, element, dnum;
NODE top = NULL;
do
{
printf("\n1.) PUSH");
printf("\n2.) POP");
printf("\n3.) DISPLAY");
printf("\n4.) EXIT");
printf("\nEnter your choice: ");
scanf("%d", &ch);
switch(ch)
{
case 1: printf("\nEnter element to push: ");
scanf("%d", &element);
push_node(&top, element);
break;
case 2: pop_node(&top);
break;
case 3: display(top);
break;
case 4: break;
default: printf("\nWrong choice!! Enter choice again.");
}
}while(ch!=4);
}
void push_node(NODE *top, int ele)
{
NODE newnode, temp;
temp = *top;
newnode = (NODE)malloc(sizeof(struct tag));
if(newnode == NULL)
{
printf("\nInsufficient memory");
return;
}
newnode->data = ele;
if(*top == NULL)
{
newnode->link = NULL;
*top = newnode;
}
else
{
newnode->link = *top;
*top = newnode;
}
}
void pop_node(NODE *top)
{
NODE c;
if(*top == NULL)
{
printf("\nStack is empty");
return;
}
c=*top;
if(c->link == NULL)
{
printf("\nPopped node: %d", c->data);
free(c);
*top = NULL;
return;
}
*top = c->link;
printf("\nPopped node: %d", c->data);
free(c);
}
void display(NODE top)
{
NODE temp;
temp = top;
if(top == NULL)
{
printf("\nStack is empty");
return;
}
printf("\nStack is: \n");
while(temp != NULL)
{
printf("\n%d", temp->data);
temp = temp->link;
}
}
Hello everybody!! Here on this blog I'll be posting C as well as C++ programs. Programs will be easier to understand as they will be implemented in a easier method and I'll b providing the necessary comments wherever required in short. Happy Programming!!!
Custom Search
Friday, November 4, 2011
Program to implement dynamically allocated Stack using linked list.
Labels:
dynamic memory allocation,
free.,
malloc,
singly linked list,
stack
Subscribe to:
Post Comments (Atom)
Custom Search
No comments:
Post a Comment