C++ Stack Implementation with Linked Lists
C++ Stack Implementation Using Linked Lists
This document demonstrates how to implement a Stack data structure in C++ using a linked list approach, including essential features like constructors, destructors, and operator overloading.
Source Code Implementation
#include <iostream>
#include <cstdlib>
class Node {
int info;
Node* next;
public:
Node(int i = 0) : info(i), next(NULL) {}
friend class Stack;
};
class Stack {
Node* first;
public:
Stack() { std::cout << "Constructor:: Stack" << std::endl; first = NULL; }
~Stack();
void insert(int data);
void remove();
Stack& operator=(const Stack&);
int operator==(const Stack&);
Stack(const Stack& p);
};
Stack::~Stack() {
std::cout << "Destructor:: Stack" << std::endl;
Node* p = first;
while (p != NULL) {
Node* q = p;
std::cout << "Deleting.." << q->info << std::endl;
p = p->next;
delete q;
}
first = NULL;
}
void Stack::insert(int data) {
Node* newNode = new Node(data);
if (first == NULL) {
first = newNode;
} else {
newNode->next = first;
first = newNode;
}
}
void Stack::remove() {
if (first != NULL) {
Node* ptr = first;
first = first->next;
delete ptr;
}
}
// Copy Constructor
Stack::Stack(const Stack& p) {
std::cout << "Constructor_Copia:: Stack" << std::endl;
first = NULL;
Node* ptr = p.first;
while (ptr != NULL) {
insert(ptr->info);
ptr = ptr->next;
}
}
Stack& Stack::operator=(const Stack& p) {
std::cout << "Overload operator =" << std::endl;
if (this != &p) {
this->~Stack();
Node* ptr = p.first;
while (ptr != NULL) {
insert(ptr->info);
ptr = ptr->next;
}
}
return *this;
}
int Stack::operator==(const Stack& p) {
std::cout << "\nOverload operator ==\n" << std::endl;
Node* ptr = first;
Node* ptr1 = p.first;
while (ptr != NULL && ptr1 != NULL) {
if (ptr->info != ptr1->info) return 0;
ptr = ptr->next;
ptr1 = ptr1->next;
}
return (ptr == NULL && ptr1 == NULL);
}
int main() {
Stack p, p1;
int data;
char c;
std::cout << "Insert data" << std::endl;
std::cin >> data;
p.insert(data);
std::cout << "Insert other data? (s/n)" << std::endl;
std::cin >> c;
while (c == 's') {
std::cout << "Insert data" << std::endl;
std::cin >> data;
p.insert(data);
std::cout << "Insert other data? (s/n)" << std::endl;
std::cin >> c;
}
p = p1;
if (p == p1) {
std::cout << "After making p == p1, we can say that they are equal" << std::endl;
}
return 0;
}