Advertisement
aleffelixf

Palindrome with Stack Java

Oct 26th, 2021
1,079
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.44 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. public class Stack<T> {
  4.  
  5.     private int stackPos;
  6.     private T[] stack;
  7.  
  8.     public Stack() {
  9.         this.stackPos = -1;
  10.         this.stack = (T[]) new Object[100];
  11.     }
  12.  
  13.     public void push(T value) {
  14.         if (this.stackPos < this.stack.length - 1) {
  15.             this.stack[++stackPos] = value;
  16.         }
  17.     }
  18.  
  19.     public T pop() {
  20.         if (this.isEmpty()) {
  21.             return null;
  22.         }
  23.         return this.stack[stackPos--];
  24.     }
  25.  
  26.     public int length() {
  27.         if (this.isEmpty()) {
  28.             return 0;
  29.         }
  30.         return this.stackPos + 1;
  31.     }
  32.  
  33.     public T head() {
  34.         if (this.isEmpty()) {
  35.             return null;
  36.         }
  37.         return this.stack[stackPos];
  38.     }
  39.  
  40.     public boolean isEmpty() {
  41.         return this.stackPos == -1;
  42.     }
  43.  
  44.     public static void main(String[] args) {
  45.         Scanner input = new Scanner(System.in);
  46.         Stack<Character> stack = new Stack<Character>();
  47.  
  48.         String answer = input.nextLine();
  49.  
  50.         for (int i = 0; i < answer.length(); i++) {
  51.             stack.push(answer.charAt(i));
  52.         }
  53.  
  54.         String reverseAnswer = "";
  55.         while (!stack.isEmpty()) {
  56.             reverseAnswer += stack.pop();
  57.         }
  58.  
  59.         if (answer.equals(reverseAnswer))
  60.             System.out.println("É um palindromo");
  61.         else
  62.             System.out.println("Não é um palindromo");
  63.     }
  64.  
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement