stack ka saare operations O(1) hota hai
stack implementation using linked list
public void push(int data)
{
StackNode newNode = new StackNode(data);
if (root == null) {
root = newNode;
}
else {
StackNode temp = root;
root = newNode;
newNode.next = temp;
}
System.out.println(data + " pushed to stack");
}
public int pop()
{
int popped = Integer.MIN_VALUE;
if (root == null) {
System.out.println("Stack is Empty");
}
else {
popped = root.data;
root = root.next;
}
return popped;
}
---------------------------------------------------------------------
queue using stack
static Stack<Integer> s1 = new Stack<Integer>();
static Stack<Integer> s2 = new Stack<Integer>();
static void enQueue(int x)
{
// Move all elements from s1 to s2
while (!s1.isEmpty())
{
s2.push(s1.pop());
//s1.pop();
}
// Push item into s1
s1.push(x);
// Push everything back to s1
while (!s2.isEmpty())
{
s1.push(s2.pop());
//s2.pop();
}
}
// Dequeue an item from the queue
static int deQueue()
{
// if first stack is empty
if (s1.isEmpty())
{
return -1;
}
// Return top of s1
int x = s1.peek();
s1.pop();
return x;
}
------------------------------------------------------------
stack using only one queue
void push(int x)
{
// Get previous size of queue
int s = q1.size();
// Push the current element
q1.add(x);
// Pop all the previous elements and put them after
// current element
for (int i = 0; i < s; i++) {
q1.add(q1.remove());
}
}
void pop()
{
// if no elements are there in q1
if (q1.isEmpty())
return;
q1.remove();
}
int top()
{
if (q1.isEmpty())
return -1;
return q1.peek();
}
-------------------------------------------------------------
stack using 2 queues
static void push(int x)
{
// Push x first in empty q2
q2.add(x);
// Push all the remaining
// elements in q1 to q2.
while (!q1.isEmpty()) {
q2.add(q1.peek());
q1.remove();
}
// swap the names of two queues
Queue<Integer> q = q1;
q1 = q2;
q2 = q;
}
static void pop()
{
// if no elements are there in q1
if (q1.isEmpty())
return;
q1.remove();
}
static int top()
{
if (q1.isEmpty())
return -1;
return q1.peek();
}
---------------------------------------------------------------
get min element using stack- see theory solution
ans- make 2 stacks. compare each element in stack 1 with top element in stack 2.
if stack1<stack2 push in stack 2
min element is top of stack 2
--------------------------------------------------------------------
stack using priority queue-
ans- priority me order daldo of coming in