Professional Documents
Culture Documents
#6
ALYAN HUSSAIN
UET-4
DATA ALGORITHMS AND
PROBLEM SOLVING
TO: MS. SOBIA YOUSAF
DATE OF SUBMISSION: 17 April 2021
Lab Tasks
Implement Stack Using Linked List:
Code:
#include <bits/stdc++.h>
using namespace std;
struct Node
{
int data;
Node *next;
};
class Stack
{public:
Node *head;
Stack() { head = NULL; }
void push(int a)
{ Node *temp;
temp = new Node;
temp->data = a;
temp->next = head;
head = temp;}
bool is_empty()
{return head == NULL;}
void pop()
{
head = head->next;}
void print_stack()
{
if (is_empty())
{cout << "The Stack is empty";
return;}
else
{
cout<<head->data<<" -> ";
do
{
head = head->next;
cout<< head->data <<" -> ";
}while(head->next);
cout<<"NULL"<<endl;}}
int peek()
DSA
{
if (is_empty())
return 0;
else
{int n = head->data;
head = head->next;
return n;}
}};
int main()
{
Stack s;
s.push(1);
s.push(8);
s.push(9);
s.push(10);
// s.pop();
// cout<<s.peek();
s.print_stack();
cout << endl;
system("pause");
return 0;
}
Output:
DSA
int head;
public:
int Stack_Array[MAX];
Stack() { head = -1; }
bool is_Empty();
bool push(int val);
int peek();
int pop();
void traverse();
};
bool Stack::is_Empty()
{ return (head < 0); }
bool Stack::push(int val)
{
if (head >= (MAX - 1))
{cout << "Stack is Already Filled!";
return false;}
else
{Stack_Array[++head] = val;
return true;}
}
int Stack::pop()
{
if (head < 0)
{cout << "Stack Underflowed Exist";
return 0;}
else
{int val = Stack_Array[head--];
return val;}
}
int Stack::peek()
{
if (head < 0)
{cout << "Stack is Empty";
return 0;}
else
return Stack_Array[head];
}
void Stack::traverse()
{
DSA
if(is_Empty())
cout<<"Stack is Empty"<<endl;
else
{
cout<<"Traversing The Stack : ";
int n = head;
while (n>=0)
{cout<<Stack_Array[n]<<" -> ";
n--;}
cout<<"NONE"<<endl;}}
int main()
{
Stack a;
for(int i = 0; i<20; i+=2)
a.push(i);
a.traverse();
cout<<"Poping Out : "<<a.pop()<<endl;
cout<<"The last value is "<<a.peek()<<endl;
system("pause");
return 0;
}
Output:
DSA