-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathImplementStckUsingQueue.C#
78 lines (65 loc) · 1.71 KB
/
ImplementStckUsingQueue.C#
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
using System;
using System.Collections;
class ImplementStckUsingQueue {
public class Stack {
// Two inbuilt queues
public Queue q1 = new Queue();
public Queue q2 = new Queue();
// To maintain current number of
// elements
public int curr_size;
public Stack()
{
curr_size = 0;
}
public void push(int x)
{
curr_size++;
// Push x first in empty q2
q2.Enqueue(x);
// Push all the remaining
// elements in q1 to q2.
while (q1.Count > 0) {
q2.Enqueue(q1.Peek());
q1.Dequeue();
}
// swap the names of two queues
Queue q = q1;
q1 = q2;
q2 = q;
}
public void pop()
{
// if no elements are there in q1
if (q1.Count == 0)
return;
q1.Dequeue();
curr_size--;
}
public int top()
{
if (q1.Count == 0)
return -1;
return (int)q1.Peek();
}
public int size()
{
return curr_size;
}
};
// Driver code
public static void Main(String[] args)
{
Stack s = new Stack();
s.push(1);
s.push(2);
s.push(3);
Console.WriteLine("current size: " + s.size());
Console.WriteLine(s.top());
s.pop();
Console.WriteLine(s.top());
s.pop();
Console.WriteLine(s.top());
Console.WriteLine("current size: " + s.size());
}
}