Check palindrome using LinkedList as queue and stack - Java Algorithm

Java examples for Algorithm:String

Description

Check palindrome using LinkedList as queue and stack

Demo Code

import java.util.LinkedList;
import java.util.Scanner;

public class Main {
  LinkedList queue = new LinkedList();
  LinkedList stack = new LinkedList();

  // Stack/*from   w w  w.  jav  a  2  s . c  o  m*/
  public void pushCharacter(char ch) {
    stack.push(ch);
  }

  public char popCharacter() {
    return (char) stack.pop();
  }

  // Queue
  public void enqueueCharacter(char ch) {
    queue.addLast(ch);
  }

  public char dequeueCharacter() {
    return (char) queue.remove(0);
  }

  public static void main(String[] args) {
    String input = "abddba";

    // Convert input String to an array of characters:
    char[] s = input.toCharArray();

    // Create a Solution object:
    Main p = new Main();

    // Enqueue/Push all chars to their respective data structures:
    for (char c : s) {
      p.pushCharacter(c);
      p.enqueueCharacter(c);
    }

    // Pop/Dequeue the chars at the head of both data structures and compare them:
    boolean isPalindrome = true;
    for (int i = 0; i < s.length / 2; i++) {
      if (p.popCharacter() != p.dequeueCharacter()) {
        isPalindrome = false;
        break;
      }
    }

    // Finally, print whether string s is palindrome or not.
    System.out.println("The word, " + input + ", is " + ((!isPalindrome) ? "not a palindrome." : "a palindrome."));
  }
}

Related Tutorials