-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.cpp
More file actions
132 lines (107 loc) · 2.2 KB
/
stack.cpp
File metadata and controls
132 lines (107 loc) · 2.2 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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
/* This file defines a generic Stack - a last in first out (LIFO) data structure.
* This data structure supports the operations - (a) push, (b) pop, (c) peek
* Author: Humayun Kabir, humayun.k1@gmail.com */
#include <iostream>
using namespace std;
//A structure to represent a node of a LinkedList
template<class T>
struct Node {
T val;
Node *next;
Node() {}
Node(const T& t, Node *p) : val(t), next(p) {}
};
//Stack class
template<class T>
class Stack {
private:
Node<T>* head;
int Size; //Represents number of elements on the stack
public:
Stack() { //Default constructor
head = NULL;
Size = 0;
}
//Pushes a new element on to the stack
void push(T val) {
Node<T>* oldHead = head;
head = new Node<T>();
head->val = val;
head->next = oldHead;
Size ++;
}
//Pops an element from the top of the stack
T pop() {
try {
if( Size >= 1 ) {
T retVal = head->val;
Node<T>* tempHead = head;
head = head->next;
delete tempHead;
Size--;
return retVal;
}
else
throw string("Stack underflow.\n");
}
catch(string s) {
cout<<s<<endl;
}
catch(...) {
cout<<"Unknown-exception occurred"<<endl;
}
}
//Returns the element from the top of the stack
T peek() {
try {
if( Size >= 1 ) {
T retVal = head->val;
return retVal;
}
else
throw string("In peek() ::Stack underflow.\n");
}
catch(string s) {
cout<<s<<endl;
}
catch(...) {
cout<<"Unknown-exception occurred"<<endl;
}
}
//Returns the size of the stack
int size() { return Size; }
//Checks if the stack is empty
bool isEmpty() { return Size == 0; }
//Prints all the elements on the stack
void iterate() {
Node<T>* tempHead = head;
while( tempHead != NULL ) {
cout<<tempHead->val<<endl;
tempHead = tempHead->next;
}
}
//Destructor
~Stack() {
while( head != NULL ) {
delete head;
head = head->next;
}
}
};
//Test the data structure
int main() {
Stack<int> s;
//push some values
s.push(5);
s.push(10);
s.push(15);
//Print the content
cout<<"The stack contains: \n";
s.iterate();
//Pop an element
cout<<"The top element is popped: " <<s.pop()<<endl;
//Print the content
cout<<"The stack contains: \n";
s.iterate();
return 0;
}