-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStack.hpp
More file actions
89 lines (76 loc) · 1.56 KB
/
Stack.hpp
File metadata and controls
89 lines (76 loc) · 1.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/*
A queue implemented with dynamic memory
Gilberto Echeverria
gilecheverria@yahoo.com
*/
#ifndef STACK_HPP
#define STACK_HPP
#include <iostream>
#include "Node.hpp"
template <class T>
class Stack {
private:
Node<T> * head = nullptr;
public:
Stack () {}
Stack (Node<T> * new_node) { head = new_node; }
~Stack() { clear(); }
bool isEmpty() { return head == nullptr; }
Node<T> * top();
Node<T> * pop();
void push(Node<T> * new_node);
void push(T data);
void clear();
};
template <class T>
Node<T> * Stack<T>::top()
{
return head;
}
template <class T>
Node<T> * Stack<T>::pop()
{
// If the list was empty
if(head == nullptr)
return nullptr;
Node<T> * item = head;
// Update the head in the list
head = head->getNext();
// Break the connection to the list
item->setNext(nullptr);
return item;
}
template <class T>
void Stack<T>::push(Node<T> * new_node)
{
// If the queue is empty
if (head == nullptr)
{
head = new_node;
}
else
{
// Make the new node point to the former head
new_node->setNext(head);
// Set the new node as head
head = new_node;
}
}
template <class T>
void Stack<T>::push(T data)
{
Node<T> * new_item = new Node<T>(data);
push(new_item);
}
template <class T>
void Stack<T>::clear()
{
Node<T> * item = head;
while (item != nullptr)
{
head = item->getNext();
delete item;
item = head;
}
}
#endif