-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack_linked_lists.cpp
More file actions
84 lines (75 loc) · 1.37 KB
/
stack_linked_lists.cpp
File metadata and controls
84 lines (75 loc) · 1.37 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
#include <iostream>
using namespace std;
template<class t>
class stack {
struct node {
t item;
node* next;
};
node* top, * cur;
public:
stack() {
top = nullptr;
}
bool isEmpty() {
return top == nullptr;
}
void push(t newItem) {
node* newItemPtr = new node;
newItemPtr->item = newItem;
newItemPtr->next = top;
top = newItemPtr;
}
void pop(t&stackTop) {
if (isEmpty())
cout << "Stack is empty.";
else {
node* temp = top;
stackTop = top->item;
top = top->next;
delete temp;
}
}
void getTop(t& stackTop) {
if (isEmpty()) {
cout << "Stack is empty.";
}
else {
stackTop = top->item;
}
}
void display() {
cur = top;
cout << "Items in the stack: ";
cout << "[";
while (cur != nullptr) {
cout << cur->item << " ";
cur = cur->next;
}
cout << "]\n";
}
};
int main()
{
stack<int> s;
int x;
// Push elements
s.push(5);
s.push(10);
s.push(4);
// Display stack
s.display(); // Output: [4 10 5]
// Get top element
s.getTop(x);
cout << "Top = " << x << endl; // Top = 4
// Pop an element
s.pop(x);
cout << "Popped = " << x << endl; // Popped = 4
// Display again
s.display(); // Output: [10 5]
// Check if stack is empty
if (s.isEmpty())
cout << "Stack is empty";
else
cout << "Stack is not empty";
}