Thursday, August 11, 2011

Data Structures (Stack operations using linked lists)

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

/*
Define the structure of the node with the data it holds and a link to another node.
*/
struct node
{
int item;
struct node *link;
};

/*
Declare a pointer top to point the TOP of the stack. Initially the pointer top is pointing to NULL
*/
struct node *top;

/*
The push function.
*/
void push(int data)
{
//create a temporary node, add data to it, link it with the stack and update the top
struct node temp;
if(&temp!=NULL) // if node is not created, then there is no memory for new node
{
temp.item = data;
temp.link = top;
top = &temp;
printf("Data Inserted\n");
}
else
printf("Stack is full");
}

/*
The pop function
*/
void pop()
{
struct node *temp;
if(top!=NULL)//top NULL implies that stack is empty
{
temp = top;
printf("popped data is:%d",temp->item);
top = top->link;
}
else
printf("Stack empty");
}

int main()
{
push(10);
push(20);
pop();
getch();
return 0;
}

No comments:

Post a Comment