-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStack.cpp
45 lines (37 loc) · 1 KB
/
Stack.cpp
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
#include "Stack.h"
Stack::Stack() {
this->head = NULL;
}
Stack::~Stack() {
}
int Stack::count() {
// Count the number of elements on the stack by iterating from the head to the tail.
int retVal = 0;
Node* currentNode = this->head;
while(currentNode != NULL) {
retVal++;
currentNode = currentNode->next;
}
return retVal;
}
void Stack::printStack() {
}
void Stack::push(Node* aNode) {
// When an element is pushed onto the stack:
// - Set the next node to be the current top of the stack.
// - Then set the new head to the newly pushed node.
aNode->next = this->head;
this->head = aNode;
}
Node* Stack::pop() {
// Pop the top-most element out of the stack.
Node* retVal = this->head;
// If the stack is not empty:
// - Set the current head to the next node.
// - And sever the connection of the popped node to the list.
if(retVal != NULL) {
this->head = retVal->next;
retVal->next = NULL;
}
return retVal;
}