-1

Hey I'm working on a program using two stacks (created using array) to determine if a string is a palindrome.

I have declared two stacks. The plan is to read in the string, one by one, and push them onto the first stack.

Then, I will pop half the stack and push them onto the second stack. I can't figure out how to pop and push half the stack.

Tan Duong
  • 1
  • 2

1 Answers1

0

So given are two stack objects, which hold no value at first:

Stack stOne, stTwo;

Assuming that you have implemented ::size(), ::push(), ::pop(), where pop returns the value stored on top of the stack, for your Stack objects, you want to push all chars of your given string into stOne. Then you will have to pop stOne for stOne.size()/2 amount of times and push the chars into stTwo:

void solvePalindrome(std::string str){
    for(int i=0; i<str.size(); i++){
        stOne.push(str[i]);
    }
    for(int i=0; i<stOne.size()/2; i++){
        stTwo.push(stOne.pop());
    }
    //do your comparison here
}

Alternatively, you can directly use str.size()/2 instead of stOne.size()/2 if you haven't implemented ::size() yet.

Note: If you have an uneven amount of characters in your string, it will round down (floor) stOne.size()/2. All code is in CPP.

pr0f3ss
  • 527
  • 1
  • 4
  • 17
  • I'm getting an error at: " stOne.push(str[i]); ". I'm not sure how to post pictures on comments but, the the prototype for my push operation is void stack::push(item entry) so pushing "push(str[i])" wouldn't work. – Tan Duong Mar 17 '19 at 20:38
  • You have to initialize the array as type char or use generic programming to allow it to have any primative type – pr0f3ss Mar 17 '19 at 20:54
  • `Stack stOne = new Stack();` will not compile in `C++`. – Fureeish Mar 17 '19 at 22:11
  • @Fureeish You are right, I got caught up with the Java constructor calling routine. To actually use the `new` keyword for creating an instance of `Stack`, you would need to change it to `Stack* stOne = new Stack();`. This would create the instance in dynamic memory, whilst with the updated `Stack stOne;` we are creating the instance in automatic storage. – pr0f3ss Mar 17 '19 at 22:45