-1

I am trying to write an algorithm/pseudo-code to check if a given array A is a palindrome using Stack.

Emanuel
  • 37
  • 8
  • 2
    have you tried anything? – Liora Haydont May 02 '18 at 13:04
  • Why would you limit yourself to usage of a Stack Data Type? Sounds suspicious like homework to me. Arrays have already random access, why use an extra data structure? – MrSmith42 May 02 '18 at 13:33
  • 1
    Try it for a small example with pen and paper. How would you do it by hand? – MrSmith42 May 02 '18 at 13:35
  • @MrSmith42 I have tried on a piece of paper and know coding too.Writing an algorithm is something else.... – Emanuel May 02 '18 at 14:05
  • @Emanuel: Try to code what you have done by hand. Compare the steps with a debugger / debug-output. – MrSmith42 May 02 '18 at 14:27
  • 2
    @MrSmith42 I did a primitive trick... Literally hand drew an array and stack and applied FILO ... Got the pseudo-code...The trouble is we are expected to use the same diction as used in the lecture slides (That's torture)....Thanks again - I think, I should pass :) – Emanuel May 02 '18 at 15:07

1 Answers1

0

Our approach would be to: - “push” elements of array a [left….right] onto a newly created stack, such that the element on the left is pushed first. Thus, the array elements are reversed such that the last element of the array is at the top of the stack.

  • Thereafter, we “pop” each element from the Stack onto a newly created array b. This means the last element of the original array a becomes the first element of new array b.

  • Finally, we compare each element of a and b and if they are equal, then the original array a is a palindrome

Algorithm Steps:

  1. Make an empty stack S

  2. Set l to left and set r to right (of array a)

  3. For each element in array a [l…r], repeat: 3.1. Add element to the top of stack S

  4. Create a new empty array b such that b [left…..right]

  5. While stack S is not empty, repeat: 5.1 Remove each element from the top of S to array b

  6. Set l to left and r to right for both arrays a and b. 6.1 If a [left….right] ≠ b [left….right]; terminate with answer false 6.2 Else a [left…right] = b [left…..right];

  7. Terminate with answer isPalindrome.

Pheww !!!!

Emanuel
  • 37
  • 8
  • I don't think this is what your professor is looking for; using an extra array is cheating. There's a way to do this by reading the input array just once; can you see how? – ruakh May 02 '18 at 15:20
  • @ruakh I am not aware the method you indicated ... Please elaborate. – Emanuel May 03 '18 at 09:12
  • I know you're not already aware of it. The challenge is to find it. :-) – ruakh May 03 '18 at 18:19