CS1020 Guess Lab4 Ex1

Link to the question – Guess Lab 4 Ex 1

import java.util.*;

class Guess
{
	public static void main(String [] args)
	{
		Scanner sc = new Scanner (System.in);
		while(sc.hasNext())
		{
			int N = sc.nextInt();
			Stack<Integer> stack = new Stack<Integer>();
			Queue<Integer> queue = new LinkedList<Integer>();
			boolean isStack = true;
			boolean isQueue = true;
			for(int i = 0; i < N; i++)
			{
				String op = sc.next();
				switch(op)
				{
					case "push":
					{
						int M = sc.nextInt();
						if(isStack)
						{
							stack.push(M);
						}
						if(isQueue)
						{
							queue.add(M);
						}
						break;
					}
					case "pop":
					{
						int M = sc.nextInt();
						if(isStack)
						{
							if(stack.size() == 0)
							{
								isStack = false;
							}
							else if(M == stack.peek())
							{
								isStack = true;
								stack.pop();
							}
							else{
								isStack = false;
							}
						}
						if(isQueue)
						{
							if(queue.size() == 0)
							{
								isQueue = false;
							}
							else if(M == queue.peek())
							{
								isQueue = true;
								queue.poll();
							}
							else
							{
								isQueue = false;
							}
						}
						break;
					}
					case "reverse":
					{
						//reverse the stack and queue
						if(isStack)
						{
							Queue<Integer> temp = new LinkedList<Integer>();
							while(stack.size() > 0)
							{
								temp.add(stack.pop());
							}
							while(temp.size() > 0)
							{
								stack.add(temp.poll());
							}
						}
						if(isQueue)
						{
							Stack<Integer> temp2 = new Stack<Integer>();
							while(queue.size() > 0)
							{
								temp2.add(queue.poll());
							}
							while(temp2.size() > 0)
							{
								queue.add(temp2.pop());
							}
						}
						break;
					}
				}
			}
			if(isQueue && isStack)
			{
				System.out.println("stack or queue");
			}
			else if(isQueue)
			{
				System.out.println("queue");
			}
			else if(isStack)
			{
				System.out.println("stack");
			}
			else
			{
				System.out.println("impossible");
			}
		}
	}
}
Advertisements
This entry was posted in NUS, SoC and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s