-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinkedStack.cpp
More file actions
108 lines (83 loc) · 1.96 KB
/
Copy pathLinkedStack.cpp
File metadata and controls
108 lines (83 loc) · 1.96 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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
/** @file
*
* @course CS1521
* @section 1
* @term Spring 2023
*
* Implementation file for a pointer-based implementation of the ADT
* stack.
*
* Adapted from pages 246-8 in Carrano 7e.
*
* @author Frank M. Carrano
* @author Timothy Henry
* @author Steve Holtz
*
* @date 06 Feb 2023
*
* @version 7.0 */
// #define NDEBUG
#include <new>
#include "LinkedStack.h"
#include <cassert>
template <typename ItemType>
LinkedStack<ItemType>::LinkedStack(const LinkedStack<ItemType>& aStack) {
if (!aStack.topPtr) {
topPtr = nullptr;
}
else {
NodePtr origStackPtr(aStack.topPtr);
try {
topPtr = new Node<ItemType>(origStackPtr->getItem() );
NodePtr newStackPtr(topPtr);
origStackPtr = origStackPtr->getNext();
while (origStackPtr) {
newStackPtr->setNext(new Node<ItemType>(origStackPtr->getItem()) );
newStackPtr = newStackPtr->getNext();
origStackPtr = origStackPtr->getNext();
}
}
catch (const std::bad_alloc&) {
while (!isEmpty() ) {
pop();
}
throw;
}
}
}
template <typename ItemType>
LinkedStack<ItemType>::~LinkedStack() {
while (!isEmpty() ) {
pop();
}
}
template <typename ItemType>
bool LinkedStack<ItemType>::isEmpty() const {
return !topPtr;
}
template <typename ItemType>
bool LinkedStack<ItemType>::push(const ItemType& newItem) {
try {
topPtr = new Node<ItemType>(newItem,
topPtr);
}
catch (const std::bad_alloc&) {
return false;
}
return true;
}
template <typename ItemType>
bool LinkedStack<ItemType>::pop() {
if (!isEmpty() ) {
NodePtr nodeToDeletePtr(topPtr);
topPtr = topPtr->getNext();
delete nodeToDeletePtr;
return true;
}
return false;
}
template <typename ItemType>
ItemType LinkedStack<ItemType>::peek() const {
assert(!isEmpty() );
return topPtr->getItem();
}