Click here to Skip to main content
15,886,578 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Java
import java.util.PriorityQueue;
import java.util.Scanner;
import java.util.Stack;

public class QS {
	 public static void main(String[] args) {
	        Scanner scan = new Scanner(System.in);
	        String input = scan.nextLine();
	        scan.close();
	char[] s = input.toCharArray();
	PriorityQueue<Character> queue=new PriorityQueue<Character>();
    Stack<Character> st = new Stack<Character>();
    for (char c : s) {
        st.push(c);
        queue.add(c);
    }
    System.out.println("STACK .... ");
    for(int i =0;i<input.length();i++){
    	System.out.println(st.pop());
    }
    System.out.println("QUEUE .... ");
    for(int i =0;i<input.length();i++){
    System.out.println(queue.poll());
    } 
    }
}


What I have tried:

I/O :

racecar
STACK ....
r
a
c
e
c
a
r
QUEUE ....
a
a
c
c
e
r
r

I am looking for "racecar" as output from the queue too.. Where am I going wrong ?
Posted
Updated 26-Oct-16 21:01pm
v3

1 solution

You chose the wrong implementing class, the priority queue, well, prioritizes some inputs with respect others (in your case uses alphabetic order as priority criterion).
Using, for instance the LinkedList implementing class, you could obtain the expected output:
Java
import java.util.LinkedList;
import java.util.Scanner;
import java.util.Stack;

public class QS {
   public static void main(String[] args) {
          Scanner scan = new Scanner(System.in);
          String input = scan.nextLine();
          scan.close();
  char[] s = input.toCharArray();
  LinkedList<Character> queue=new LinkedList<Character>();
    Stack<Character> st = new Stack<Character>();
    for (char c : s) {
        st.push(c);
        queue.add(c);
    }
    System.out.println("STACK .... ");
    for(int i =0;i<input.length();i++){
      System.out.println(st.pop());
    }
    System.out.println("QUEUE .... ");
    for(int i =0;i<input.length();i++){
    System.out.println(queue.poll());
    }
    }
}
 
Share this answer
 
Comments
Karthik_Mahalingam 28-Oct-16 8:01am    
5

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900