0% found this document useful (0 votes)
5 views3 pages

C++ Stack and Queue Implementation

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

C++ Stack and Queue Implementation

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

Program-5

#include <iostream>

#include <vector>

#include <stdexcept>

// Abstract base class LIST with pure virtual functions

template <typename T>

class LIST {

public:

// Pure virtual function to store a value

virtual void store(const T& value) = 0;

// Pure virtual function to retrieve a value

virtual T retrieve() = 0;

// Virtual destructor for proper cleanup in derived classes

virtual ~LIST() = default;

};

// Derived class Stack from LIST

template <typename T>

class Stack : public LIST<T> {

private:

std::vector<T> data;

public:

// Override store: pushes the value onto the top of the stack

void store(const T& value) override {

data.push_back(value);

}
// Override retrieve: pops and returns the top value from the stack

T retrieve() override {

if ([Link]()) {

throw std::runtime_error("Stack is empty");

T value = [Link]();

data.pop_back();

return value;

};

// Derived class Queue from LIST

template <typename T>

class Queue : public LIST<T> {

private:

std::vector<T> data;

public:

// Override store: adds the value to the rear of the queue

void store(const T& value) override {

data.push_back(value);

// Override retrieve: removes and returns the value from the front of the queue

T retrieve() override {

if ([Link]()) {

throw std::runtime_error("Queue is empty");

T value = [Link]();

[Link]([Link]()); // Note: Inefficient for large queues; use std::deque for better
performance
return value;

};

// Example usage (for demonstration)

int main() {

// Create a stack

Stack<int> myStack;

[Link](10);

[Link](20);

std::cout << "Stack retrieve: " << [Link]() << std::endl; // Outputs: 20

// Create a queue

Queue<int> myQueue;

[Link](10);

[Link](20);

std::cout << "Queue retrieve: " << [Link]() << std::endl; // Outputs: 10

return 0;

You might also like