[go: up one dir, main page]

0% found this document useful (0 votes)
22 views4 pages

Ali Irtza Haider-231259-Queue and Stack

queue and stacks

Uploaded by

233053
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views4 pages

Ali Irtza Haider-231259-Queue and Stack

queue and stacks

Uploaded by

233053
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

Lab Task 5

DSA LAB
Submitted By: Ali Irtza Haider(231259)
Submitted To: Mr. Abdullah Imran

BSCYS-3-B-F23
Task 1
Code:

#pragma once

#include <iostream>

struct Node {
int data;
Node* next;

Node(int _data) : data(_data), next(nullptr) {}


};

class Stack {
private:
Node* top;
int size;

public:
Stack() : top(nullptr), size(0) {}

~Stack() {
while (top) {
Node* temp = top;
top = top->next;
delete temp;
}
}

void push(int data) {


Node* newNode = new Node(data);
newNode->next = top;
top = newNode;
size++;
}

int pop() {
if (!top) return -1;
int poppedData = top->data;
Node* temp = top;
top = top->next;
delete temp;
size--;
return poppedData;
}

int peek() const {


return top ? top->data : -1;
}

void display() const {


Node* current = top;
while (current) {
std::cout << current->data << " ";
current = current->next;
}
std::cout << std::endl;
}

int getSize() const {


return size;
}
};

Output:
Task 2:

#pragma once

#include <iostream>

struct Node {
int data;
Node* next;

Node(int _data) : data(_data), next(nullptr) {}


};

class Queue {
private:
Node* front;
Node* rear;
int size;

public:
Queue() : front(nullptr), rear(nullptr), size(0) {}

~Queue() {
while (front) {
Node* temp = front;
front = front->next;
delete temp;
}
}

void enqueue(int data) {


Node* newNode = new Node(data);
if (!rear) {
front = rear = newNode;
} else {
rear->next = newNode;
rear = newNode;
}
size++;
}

int dequeue() {
if (!front) return -1;
int dequeuedData = front->data;
Node* temp = front;
front = front->next;
if (!front) rear = nullptr;
delete temp;
size--;
return dequeuedData;
}

int frontElement() const {


return front ? front->data : -1;
}

void display() const {


Node* current = front;
while (current) {
std::cout << current->data << " ";
current = current->next;
}
std::cout << std::endl;
}

int getSize() const {


return size;
}
};

You might also like