-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTDynamicStack.h
103 lines (91 loc) · 1.6 KB
/
TDynamicStack.h
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
#ifndef TDYNAMICSTACK_H
#define TDYNAMICSTACK_H
#include <iostream>
#include <string>
using namespace std;
template <class T>
class TDynamicStack{
private:
struct Node {
T value;
Node *next;
};
Node *head; // head pointer
Node *top;
public:
TDynamicStack(){head = NULL; top = NULL;} // constructor
~TDynamicStack(); //destructor
bool isEmpty(void);
void peek(void);
void push(T val);
T pop(T &val);
};
template <class T>
TDynamicStack<T> :: ~TDynamicStack()
{
Node *nodePtr, *nextNode;
nodePtr = head;
while (nodePtr != NULL)
{
nextNode = nodePtr->next;
delete nodePtr;
nodePtr = nextNode;
}
}
template <class T>
void TDynamicStack<T> :: push(T val){
Node *newNode, *nodePtr;
newNode = new Node;
newNode->value = val;
newNode->next = NULL;
if (!head){
head = newNode;
top = newNode;
}
else
{
nodePtr = head;
while (nodePtr -> next){
nodePtr = nodePtr -> next;
}
nodePtr -> next = newNode;
top = newNode;
}
}
template <class T>
T TDynamicStack<T> :: pop(T &val){
Node *preNode, *curNode;
curNode = head;
while (head != NULL){
if (curNode->next != NULL){
preNode = curNode;
curNode = curNode->next;
}
else{
preNode->next = NULL;
if (curNode != NULL){
val=curNode->value;
delete curNode;
}
top = preNode;
return val;
}
}
return 0;
}
template <class T>
bool TDynamicStack<T> :: isEmpty(void)
{
if (head){
return false;
}
else{
return true;
}
}
template <class T>
void TDynamicStack<T> :: peek(void)
{
cout<<top->value<<endl;
}
#endif