#include <iostream.h>
#include <conio.h>
#include <stdlib.h>
class stack
{
private:
int data;
stack *next;
public:
stack() {next = NULL;}
friend void create(); //function to create a node
friend void push(stack *&,int); //function to push item on stack
friend stack* pop(stack *&); //function to delete item from stack
int getdata() {return data;} //function to return the data of particular node
~stack() {delete next;}
};
stack *New,*head,*top;
void create()
{
New = new stack;
New -> next = NULL;
}
void push (stack *&nd,int Item)
{
if(nd == NULL) //if first node
{
nd = new stack; //create first node
nd -> next = NULL; //initialize next pointer field
nd -> data = Item; //push item
head = nd; //update head
top = nd; //update top
return;
}
create(); //create a node
New -> data = Item; //push item
top -> next = New; //add to list
top = New; //update top
}
stack* pop (stack *&nd)
{
if(nd == NULL) //if stack is empty
{
cout << "\nStack Underflow";
cout << "\nPress any key to halt...\n";
getch();
exit(0);
}
stack *deleted;
if(top == nd) //if only one node
{
deleted = nd;
top = NULL;
nd = NULL;
return deleted;
}
deleted = top;
stack *temp = head;
while(temp -> next != top) //goto secondlast node
temp = temp -> next;
temp -> next = NULL;
top = temp; //update top
return deleted;
}
int main()
{
stack *s = NULL;
for(int i = 1;i <= 5;i++) //push 5 items to list
push(s,5*i);
for(int i = 1;i <= 5;i++)
{
stack *result = pop(s); //pop items and
cout << result -> getdata() << ' '; //display
}
getch();
return 0;
}
OUTPUT
25 20 15 10 5
Download Original File
Stack using C++.cpp
No comments:
Post a Comment