Advertisement
Guest User

palindromestack

a guest
Dec 10th, 2019
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.88 KB | None | 0 0
  1. class Solution {
  2.   /**
  3.    * Checks for a String represented as a SLList whether this String is a palindrome.
  4.    * This is done by using a stack.
  5.    *
  6.    * An empty String or null should return true.
  7.    *
  8.    * @param list
  9.    *     SLList used to represent a String
  10.    * @return true if the String represented as a SLList is a palindrome, otherwise false
  11.    */
  12.   public static boolean checkPalindrome(SLList list) {
  13.     LibraryStack<Character> stack = new LibraryStack<>();
  14.     if (list == null || list.size() < 2) {
  15.       return true;
  16.     }
  17.     int n = list.size();
  18.     for(int i = 0; i < n/2; i++) {
  19.       stack.push(list.removeFirst());
  20.     }
  21.     if(n % 2 == 1) {
  22.       list.removeFirst();
  23.     }
  24.     for(int i = 0; i < n/2; i++) {
  25.       if(stack.pop() != list.removeFirst()) {
  26.         return false;
  27.       }
  28.     }
  29.     return true;
  30.   }
  31. }
  32.  
  33. // class Solution {
  34. //   /**
  35. //    * Checks for a String represented as a SLList whether this String is a palindrome.
  36. //    * This is done by using a stack.
  37. //    *
  38. //    * An empty String or null should return true.
  39. //    *
  40. //    * @param list
  41. //    *     SLList used to represent a String
  42. //    * @return true if the String represented as a SLList is a palindrome, otherwise false
  43. //    */
  44. //   public static boolean checkPalindrome(SLList list) {
  45. //     LibraryStack<Character> stack = new LibraryStack<>();
  46. //     if (list == null || list.size() <= 1) {
  47. //       return true;
  48. //     }
  49. //     while(stack.size() != list.size()) {
  50. //       char temp = list.removeFirst();
  51. //       stack.push(temp);
  52. //       if(list.size() == stack.size()+1) {
  53. //         list.removeFirst();
  54. //       }
  55. //     }
  56. //     while(!stack.isEmpty()) {
  57. //       char temp = stack.pop();
  58. //       char temp1 = list.removeFirst();
  59. //       if (temp != temp1) {
  60. //         return false;
  61. //       }
  62. //     }
  63. //     return true;
  64. //   }
  65. // }
  66. //
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement