-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlinked_list_stack.cpp
113 lines (103 loc) · 1.62 KB
/
linked_list_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
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
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
template <class T>
struct node
{
T data;
node<T> *next;
};
template <class T>
class Stack
{
node<T> *top;
unsigned long long int start;
public:
// Constructor
Stack()
{
start = time(nullptr);
top = nullptr;
}
// Destructor
~Stack()
{
while (top != nullptr)
{
node<T> *temp = top->next;
delete top;
top = temp;
}
delete top;
cout << time(nullptr) - start;
}
// Function to insert data in Stack
void push(T data);
// Function to display all elements of stack
void display();
// Function to pop element from stack
T pop();
};
template <class T>
void Stack<T>::push(T data)
{
node<T> *temp = new node<T>;
temp->data = data;
temp->next = top;
top = temp;
}
template <class T>
void Stack<T>::display()
{
if (top == nullptr)
{
cout << "Cannot Display: Stack Empty \n";
exit(1);
}
else
{
node<T> *temp;
temp = top;
while (temp != nullptr)
{
cout << temp->data << endl;
temp = temp->next;
}
delete temp;
}
}
template <class T>
T Stack<T>::pop()
{
if (top == nullptr)
{
cout << "Cannot Pop: Stack Empty \n";
exit(1);
}
node<T> *temp;
temp = top;
top = temp->next;
// Save popped data in a temporary variable
T popped = temp->data;
// Delete the popped node
delete temp;
// Return the popped data
return popped;
}
int main()
{
Stack<char> s;
s.push('a');
s.push('b');
s.push('c');
s.push('d');
s.display();
s.pop();
s.display();
s.pop();
s.pop();
s.pop();
s.display();
return 0;
}