Java Day 18: Queues and Stacks



Write the following declarations and implementations:

Two instance variables: one for your stack, and one for your queue.
A void pushCharacter(char ch) method that pushes a character onto a stack.
A void enqueueCharacter(char ch) method that enqueues a character in the queue instance variable.
A char popCharacter() method that pops and returns the character at the top of the stack instance variable.



  1. import java.io.*;
  2. import java.util.*;
  3. public class Solution {
  4. private LinkedList stack;
  5. private LinkedList queue;
  6. public Solution() {
  7. this.stack = new LinkedList();
  8. this.queue = new LinkedList();
  9. }
  10. private char popCharacter() {
  11. return (char) this.stack.pop();
  12. }
  13. private void pushCharacter(char c) {
  14. this.stack.push(c);
  15. }
  16. private char dequeueCharacter() {
  17. return (char) this.queue.remove(0);
  18. }
  19. private void enqueueCharacter(char c) {
  20. this.queue.addLast(c);
  21. }
  22. public static void main(String[] args) {
  23. Scanner scan = new Scanner(System.in);
  24. String input = scan.nextLine();
  25. scan.close();
  26. // Convert input String to an array of characters:
  27. char[] s = input.toCharArray();
  28. // Create a Solution object:
  29. Solution p = new Solution();
  30. // Enqueue/Push all chars to their respective data structures:
  31. for (char c : s) {
  32. p.pushCharacter(c);
  33. p.enqueueCharacter(c);
  34. }
  35. // Pop/Dequeue the chars at the head of both data structures and compare them:
  36. boolean isPalindrome = true;
  37. for (int i = 0; i < s.length/2; i++) {
  38. if (p.popCharacter() != p.dequeueCharacter()) {
  39. isPalindrome = false;
  40. break;
  41. }
  42. }
  43. //Finally, print whether string s is palindrome or not.
  44. System.out.println( "The word, " + input + ", is "
  45. + ( (!isPalindrome) ? "not a palindrome." : "a palindrome." ) );
  46. }
  47. }