Approach: Using two stacks and a variable say '"front". Here are the algorithms for the queue operations:
- Enqueue:
- IF Stack1.Empty Then front = element
- Stack1.Push(element)
- Dequeue:
- IF Stack2.Empty Then
- WHILE NOT Stack1.Empty
- Stack2.Push(Stack1.Pop())
- Return Stack2.Pop()
- Peek:
- IF NOT Stack2.Empty
- Return Stack2.Peek()
- Return front
- Empty:
- Return Stack1.Empty AND Stack2.Empty
Implementation in C#:
public class MyQueue
{
public MyQueue()
{
this.stack1 = new Stack<int>();
this.stack2 = new Stack<int>();
}
public void Enqueue(int x)
{
if (this.stack1.Count <= 0)
{
this.front = x;
}
this.stack1.Push(x);
}
public int Dequeue()
{
if (this.stack2.Count <= 0)
{
while(this.stack1.Count > 0)
{
this.stack2.Push(this.stack1.Pop());
}
}
return this.stack2.Pop();
}
public int Peek()
{
if(this.stack2.Count > 0)
{
return this.stack2.Peek();
}
if (this.stack1.Count > 0)
{
return this.front;
}
return -1;
}
public bool Empty()
{
return this.stack1.Count <= 0 && this.stack2.Count <= 0;
}
int front;
private Stack<int> stack1;
private Stack<int> stack2;
}
Complexity: Pop - O(n) and for rest of operations O(1)
No comments:
Post a Comment