/*******************************************************
APPLICATION : Stack Implementation of Linked List
CODED BY : Ankit Pokhrel
COMPILED ON : Borland C++ Ver 5.02
DATE : 2010 - June - 29
********************************************************/
#include "iostream.h"
#include "conio.h"
#include "process.h"
struct Stack //Structure to represent Stack
{
int data;
struct Stack *next; //Pointer to next node
};
typedef struct Stack node; //Now, node represent Structure Stack
node *New,*head = NULL,*top = NULL; //Global Variables
void create()
{
New = new node; //Create a new node
New -> data = NULL; //Initialize data
New -> next = NULL; //Initialize next pointer field
if(head == NULL) //if first node
{
head = New; //Initialize head
top = New; //Update top
}
}
void push(int ITEM)
{
node *temp = head;
if(head == NULL) //if First Item is Pushed to Stack
{
create(); //Create a Node
head -> data = ITEM; //Insert Item to head of List
return; //Exit from Function
}
create(); //Create a new Node
New -> data = ITEM; //Insert Item
while(temp -> next != NULL)
temp = temp -> next; //Go to Last Node
temp -> next = New; //Point New node
top = New; //Update top
}
node* pop()
{
node *temp = head,*deleted;
if(top == NULL) //If the Stack is Empty
{
cout << "\nStack Underflow";
exit(0); //Exit from Program
}
if(top == head) //If only one Item
{
deleted = head;
head = top = NULL; //Set head and top to Null
return deleted; //Return deleted node
}
while(temp -> next != top)
temp = temp -> next; //move pointer temp to second last node
temp -> next = NULL; //Second last node points to NULL
deleted = top; //Save topmost node
top = temp; //Update top
return deleted; //Return deleted node
}
void display()
{
if(head == NULL) //if no items
{
cout << "Stack is empty";
return;
}
node *temp = head;
cout << temp -> data << ' '; //Print First Item
while(temp -> next != NULL)
{
temp = temp -> next; //Move to next node
cout << temp -> data << ' '; //Print Next Item
}
}
int main()
{
node *n;
int i;
for(i = 1;i <= 5;i++)
push(5*i); //Push 5 elements on Stack
cout << "The elements of Stack are : ";
display(); //Display all Elements
for(i = 1;i <= 5;i++)
{
n = pop(); //Pop elements
cout << endl << "\nDeleted Item : " << n -> data << endl; //Display deleted element
cout << "The elements of Stack are : ";
display(); //Display all Elements
}
cout << "\n\nThis is Stack Underflow Condition (No Items on Stack).";
getch();
n = pop(); //Stack Underflow Condition (no Items on Stack)
return 0;
}
......................
Labels:
Linked List,
Stack
No comments:
Post a Comment