Monday, 25 August 2014

Stack using Linked List

#include "stdafx.h"
#include<iostream>
using namespace std;
struct Link
{
int data;
Link *next;
};
class Stack
{
private:
Link *top;
public:
Stack()
{
top=NULL;
}
void push_values(int d)
{
Link *ptr,*temp;
if(top==NULL)
{
top=new Link;
top->data=d;
top->next=NULL;
}
else
{
ptr=top;
while(ptr->next!=NULL)
ptr=ptr->next;
temp=new Link;
temp->data=d;
temp->next=NULL;
ptr->next=temp;
}
}
int pop_values()
{
Link *ptr,*temp;
temp=top;
if(top==NULL)
{
cout<<"\nStack is empty:"<<endl;
return -1;
}
int flag=0;
ptr=temp;
while(temp->next!=NULL)
{
flag=1;
ptr=temp;
temp=temp->next;
}
if(flag==0)
{
top=NULL;
}
ptr->next=NULL;
int value=temp->data;
delete temp;
return value;
}
void get_values()
{
Link *temp;
temp=top;
while(temp!=NULL)
{
cout<<temp->data<<"  ";
temp=temp->next;
}
}
};
int main()
{
Stack s1;
int choice,value;
do
{
cout<<"\n\n\t\t\t-----Main Menu-----\n\n\t\tPlease select your choice (1-3):\n\n1)Push\n2)Pop\n3)Exit\n";
cin>>choice;
if(choice==1)
{
cout<<"\nEnter an Integer:\n";
cin>>value;
s1.push_values(value);
cout<<"\nRemaining values are...\n";
s1.get_values();
}
else if(choice==2)
{
cout<<"Popped Value is "<<"  "<<s1.pop_values()<<"\n";
cout<<"\nRemaining values are...\n";
s1.get_values();
}
else if(choice==3)
{
exit(0);
}
else
{
cout<<"\nInvalid choice!!!Try again...\n";
}
}
while(choice!=3);
return 0;
}


No comments:

Post a Comment