File tree 1 file changed +76
-0
lines changed
Course 2 - Data Structures in JAVA/Lecture 10 - Queues
1 file changed +76
-0
lines changed Original file line number Diff line number Diff line change 65
65
-1
66
66
false
67
67
*/
68
+ import java.util.*;
69
+ public class Stack {
70
+
71
+ //Define the data members
72
+ private Queue<Integer> q1;
73
+ private Queue<Integer> q2;
74
+ private int size;
75
+
76
+
77
+ public Stack() {
78
+ //Implement the Constructor
79
+ q1=new LinkedList<Integer>();
80
+ q2=new LinkedList<Integer>();
81
+ size=0;
82
+ }
83
+
84
+
85
+
86
+ /*----------------- Public Functions of Stack -----------------*/
87
+
88
+
89
+ public int getSize() {
90
+ //Implement the getSize() function
91
+ return size;
92
+ }
93
+
94
+ public boolean isEmpty() {
95
+ //Implement the isEmpty() function
96
+ return size==0;
97
+ }
98
+
99
+ public void push(int element) {
100
+ //Implement the push(element) function
101
+ q1.add(element);
102
+ size=size+1;
103
+ }
104
+
105
+ public int pop() {
106
+ //Implement the pop() function
107
+ if (q1.isEmpty())
108
+ {
109
+ return -1;
110
+ }
111
+ while(q1.size()!=1)
112
+ {
113
+ q2.add(q1.remove());
114
+ }
115
+ int top=q1.remove();
116
+
117
+ while(!q2.isEmpty())
118
+ {
119
+ q1.add(q2.remove());
120
+ }
121
+ size=size-1;
122
+ return top;
123
+ }
124
+
125
+ public int top() {
126
+ //Implement the top() function
127
+ if (q1.isEmpty())
128
+ {
129
+ return -1;
130
+ }
131
+ while(q1.size()!=1)
132
+ {
133
+ q2.add(q1.remove());
134
+ }
135
+ int top=q1.peek();
136
+ q2.add(q1.remove());
137
+
138
+ Queue<Integer> q=q1;
139
+ q1=q2;
140
+ q2=q;
141
+ return top;
142
+ }
143
+ }
You can’t perform that action at this time.
0 commit comments