Brumski's DSA Learning Project 1.3
For Learning Data Structures and Algorithms in C++
Loading...
Searching...
No Matches
stack_dsa.hpp
1#pragma once
2#include <memory>
3#include <iostream>
4
8void UsingStack();
9
13void UsingStack2();
14
20template<class T>
21class MyStack {
22private:
26 template<class NType>
27 class Node {
28 public:
30 std::unique_ptr<Node<NType>> next = nullptr;
35 Node() = default;
36 };
37public:
41 MyStack() = default;
42
46 MyStack(const MyStack<T>&) = delete;
47
52 MyStack(MyStack<T>&& other) noexcept = default;
53
57 MyStack<T>& operator=(const MyStack<T>&) = delete;
58
63 MyStack<T>& operator=(MyStack<T>&& other) noexcept = default;
64private:
65 std::unique_ptr<Node<T>> myTop;
67public:
71 virtual T Top() {
72 return myTop->data;
73 }
74
79 virtual MyStack<T>& push_top(const T& value) {
80 std::unique_ptr<Node<T>> newNode = std::make_unique<Node<T>>();
81 newNode->data = value;
82 newNode->next = std::move(myTop);
83 myTop = std::move(newNode);
84
85 return *this;
86 }
87
91 virtual MyStack<T>& popTop() {
92 myTop = std::move(myTop->next);
93 return *this;
94 }
95
99 virtual bool isEmpty() {
100 if (myTop) return false;
101 else return true;
102
103 return false;
104 }
105};
106
111template<class T>
112void UsingStack3(MyStack<T>& object1) {
113 while (!object1.isEmpty()) {
114 std::cout << "The top element is " << object1.Top() << std::endl;
115 object1.popTop();
116 }
117}
This is a template class that represents a single element of a stack, and it will be called "Node".
Definition stack_dsa.hpp:27
std::unique_ptr< Node< NType > > next
Stores the address of the next node.
Definition stack_dsa.hpp:30
Node()=default
Default Constructor.
NType data
Stores the data for each node.
Definition stack_dsa.hpp:29
This is a template class that represents the stack data structure.
Definition stack_dsa.hpp:21
MyStack(const MyStack< T > &)=delete
Deleted copy constructor.
MyStack(MyStack< T > &&other) noexcept=default
Default Move constructor.
std::unique_ptr< Node< T > > myTop
Pointer to the top element of the stack.
Definition stack_dsa.hpp:65
MyStack< T > & operator=(MyStack< T > &&other) noexcept=default
Default Move assignment operator.
virtual T Top()
Returns the top element of the stack.
Definition stack_dsa.hpp:71
MyStack< T > & operator=(const MyStack< T > &)=delete
Deleted copy assignment operator.
virtual MyStack< T > & push_top(const T &value)
Pushes a new element to the top of the stack.
Definition stack_dsa.hpp:79
virtual bool isEmpty()
Returns true if the stack is empty.
Definition stack_dsa.hpp:99
MyStack()=default
Default Constructor.
virtual MyStack< T > & popTop()
Removes the top element of the stack.
Definition stack_dsa.hpp:91