-
Notifications
You must be signed in to change notification settings - Fork 0
/
inclasslabQ2.cpp
89 lines (80 loc) · 1.97 KB
/
inclasslabQ2.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
#include <iostream>
using namespace std;
// Define the node structure
struct Node {
int data;
Node* next;
};
class Stack {
private:
Node* top;
public:
Stack() {
top = NULL;
}
// Check if stack is empty
bool isEmpty() {
return top == NULL;
}
// Push element on top of stack
void push(int val) {
Node* newNode = new Node;
newNode->data = val;
newNode->next = top;
top = newNode;
}
// Pop element from top of stack
int pop() {
if (isEmpty()) {
cout << "Stack is empty" << endl;
return -1;
}
int data = top->data;
Node* temp = top;
top = top->next;
delete temp;
return data;
}
// Get the top element of stack
int peek() {
if (isEmpty()) {
cout << "Stack is empty" << endl;
return -1;
}
return top->data;
}
// Display the stack
void display() {
if (isEmpty()) {
cout << "Stack is empty" << endl;
return;
}
Node* curr = top;
while (curr != NULL) {
cout << curr->data << " ";
curr = curr->next;
}
cout << endl;
}
};
int main() {
Stack Linkedlist;
Linkedlist.display();
Linkedlist.push(1);
Linkedlist.display();
Linkedlist.push(2);
Linkedlist.display();
Linkedlist.push(3);
Linkedlist.display();
Linkedlist.push(4);
Linkedlist.display(); // 4 3 2 1
cout << "Top element is " << Linkedlist.peek() << endl; // 4
cout << "Element is going to pop " << Linkedlist.peek() << endl;
Linkedlist.pop();
Linkedlist.display();
cout << "Element is going to pop " << Linkedlist.peek() << endl;
Linkedlist.pop();
Linkedlist.display(); // 2 1
cout << "Top element is " << Linkedlist.peek() << endl; // 2
return 0;
}