-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlinkedList1.cpp
106 lines (83 loc) · 2.06 KB
/
linkedList1.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
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node* next;
};
class Stack {
private:
Node* top;
public:
Stack() {
top = NULL;
}
bool is_empty() {
return top ==NULL;
}
void push(int value) { //implementing push function
Node* new_node = new Node;
new_node->data = value;
new_node->next = top;
top = new_node;
}
int pop() {
if (is_empty()) {
cout << "Error: Stack underflow\n";
return -1;
}
Node* temp = top;
int data = temp->data; //popping elements by giving the value
top = top->next;
delete temp;
return data;
}
int peek() {
if (is_empty()) {
cout << "Error: Stack empty\n";
return -1;
}
return top->data;
}
int size() {
int count = 0;
Node* temp = top;
while (temp != NULL) {
count++;
temp = temp->next;
}
return count;
}
};
void prints (Stack s){
if (s.is_empty()){
return;
}
int x = s.peek();
s.pop();
prints(s);
cout << x << " ";
s.push(x);
}
int main() {
Stack s;
s.push(1);
s.push(2);
s.push(3);
cout << "The stack: ";
prints(s);
cout << endl;
cout << "Size of stack: " << s.size() << endl;
cout << "Top element: " << s.peek() << endl;
s.pop();
cout << "after popping : ";
prints(s);
cout << endl;
cout << "Top element after popping : " << s.peek() << endl;
s.push(4);
cout << "after pushing : ";
prints(s);
cout << endl;
cout << "Top element after pushing: " << s.peek() << endl;
return 0;
}