Stack Using Linked List Data Structure Code

 

Stack Using Linked List Watch Video Click Here


Source Code

#include<iostream>
#include<conio.h>
using namespace std;
class Node
{
private:
int data;
Node *next;
public:
void setData(int n)
{
data = n;
}
int getData()
{
return data;
}
void setNext(Node *ptr)
{
next = ptr;
}
Node* getNext()
{
return next;
}
};
class Stack
{
private:
Node *head;
public:
Stack()
{
head = NULL;
}
void push(int n)
{
Node *current = new Node;
current -> setData(n);
current -> setNext(head);
head = current;
cout<<"\n\n Value Push "<<n;
}
void pop()
{
if(head == NULL)
{
cout<<"\n\n Stack is Empty...";
}
else
{
Node *ptr = head;
head = head -> getNext();
cout<<"\n\n Value Pop "<<ptr -> getData();
delete ptr;
}
}
void display()
{
if(head == NULL)
{
cout<<"\n\n Stack is Empty...";
}
else
{
cout<<"\n\n Stack Values:";
Node *ptr = head;
while(ptr != NULL)
{
cout<<" "<<ptr -> getData();
ptr = ptr -> getNext();
}
}
}
void search(int n)
{
if(head == NULL)
{
cout<<"\n\n Stack is Empty...";
}
else
{
int found=0;
Node *ptr = head;
while(ptr != NULL)
{
if(n == ptr -> getData())
{
cout<<"\n\n Search Value : "<<ptr -> getData();
found++;
}
ptr = ptr -> getNext();
}
if(found == 0)
{
cout<<"\n\n Value Can't Found...";
}
}
}
void update(int n)
{
if(head == NULL)
{
cout<<"\n\n Stack is Empty...";
}
else
{
int found=0;
Node *ptr = head;
while(ptr != NULL)
{
if(n == ptr -> getData())
{
cout<<"\n\n New Value : ";
cin>>n;
ptr -> setData(n);
cout<<"\n\n Value Updated Successfully...";
found++;
}
ptr = ptr -> getNext();
}
if(found == 0)
{
cout<<"\n\n Value Can't Found...";
}
}
}
};
main()
{
Stack s;
p:
system("cls");
int choice,n;
cout<<"\n\n 1. Push";
cout<<"\n\n 2. Pop";
cout<<"\n\n 3. Display";
cout<<"\n\n 4. Search";
cout<<"\n\n 5. Update";
cout<<"\n\n 6. Exit";
cout<<"\n\n\n Select One Option (1-6) : ";
cin>>choice;
switch(choice)
{
case 1:
cout<<"\n\n Enter Value : ";
cin>>n;
s.push(n);
break;
case 2:
s.pop();
break;
case 3:
s.display();
break;
case 4:
cout<<"\n\n Enter Value : ";
cin>>n;
s.search(n);
break;
case 5:
cout<<"\n\n Enter Value : ";
cin>>n;
s.update(n);
break;
case 6:
exit(0);
default:
cout<<"\n\n\n Invalid Option...Please Try Again...";
}
getch();
goto p;
}

Post a Comment

Previous Post Next Post