Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Solver
- {
- public static void main(String args[])
- {
- }
- }
- class Stack // using two Queues
- {
- Queue q = new Queue();
- public void push(int d)
- {
- q.push(d);
- }
- public Node pop()
- {
- if (isEmpty())
- {
- System.out.println("The Stack is Empty");
- return null;
- }
- Queue qq = new Queue();
- while (q.front().next != null)
- {
- qq.push(q.pop().data);
- }
- Node temp = q.pop();
- while (qq.isEmpty() == false)
- {
- q.push(qq.pop().data);
- }
- return temp;
- }
- public Node top()
- {
- if (isEmpty())
- {
- System.out.println("The Stack is Empty");
- return null;
- }
- Queue qq = new Queue();
- Node temp = null;
- while (isEmpty() == false)
- {
- temp = q.pop();
- qq.push(temp.data);
- }
- while (qq.isEmpty() == false)
- {
- q.push(qq.pop().data);
- }
- return temp;
- }
- public boolean isEmpty()
- {
- return q.isEmpty();
- }
- }
- class Node
- {
- int data;
- Node next;
- public Node(int d)
- {
- data = d;
- }
- }
- class Queue
- {
- Node front, tail;
- public void push(int d)
- {
- Node temp = new Node(d);
- if (tail == null)
- {
- front = temp;
- tail = temp;
- return;
- }
- tail.next = temp;
- tail = temp;
- return;
- }
- public Node pop()
- {
- if (isEmpty())
- {
- System.out.println("Can't pop, The Queue is Empty");
- return null;
- }
- Node temp = front;
- front = front.next;
- if (front == null)tail = null;
- return temp;
- }
- public void display() {
- if (isEmpty())
- {
- System.out.print("The Queue is Empty");
- }
- Node cur = front;
- while (cur != null)
- {
- System.out.print(cur.data + " ");
- cur = cur.next;
- }
- System.out.println();
- return;
- }
- public Node front()
- {
- if (isEmpty())
- {
- System.out.print("The Queue is Empty");
- }
- return front;
- }
- public boolean isEmpty()
- {
- return front == null;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment