1

I am trying to build a palindrome checker using stacks and a Linked List. I am using generics in order to reuse the nodes and structures to complete two parts of this assignment (to accomplish something different in the next part).

The program is not pushing the letters onto the stack- it is returning nulls. I believe the problem is with the construction of the push method, either in the LinkedStack construction, or the StackDriver implementation, or both. I am just not sure what I am doing wrong; I have tried a multitude of alternatives, and have looked up and tried other methods to construct the push methods but then I get errors and can’t get the program to run at all. (I realize the 2 push methods I have here are different- these are 2 versions I have tried). Should I be looking at some type of boxing for the char c to use the wrapper class?

The program has been set back to the last point at which it ran. The “reversed” popped element seems to be getting the correct amount of characters though- why?

I realize there are other problems with this program as well but I feel like I can’t address them until I get past this stumbling block. Any assistance would be appreciated- thank you!

Mike

The given interface:

public interface Stack<E> {
   void push(E data);
   E pop();
   boolean isEmpty();
   int size();
   E stackTop();
   void clear();
}

The Node and methods:

public class Node<E>  {

// create the node structure
    private E data;
    private Node<E> next;


    // getters and setters  
    public E getData() {
        return data;
    }
    public void setData(E data) {
        this.data = data;
    }
    public Node<E> getNext() {
        return next;
    }
    public void setNext(Node<E> next) {
        this.next = next;
    }

}

The Stack:

import java.util.EmptyStackException;


public class LinkedStack<E> implements Stack<E>{

// Create the head and nodeCount variables
private Node<E> head;
private int nodeCount;

// also need to be able to convert letters to capitals.

// constructor for the LinkedStack
public LinkedStack()
{
    clear();
}


// A method to push the data onto a stack and increment the node count
public void push(E data) {
    head = new Node<E>();
    nodeCount++;
    }


// pop the head off of the stack and decrement the node count
public E pop() {
    E item;

    if (head == null)
        throw new EmptyStackException();

    item = head.getData();
    head = head.getNext();
    nodeCount--;
    return item;
}


// Check if the stack is empty
public boolean isEmpty() {
    if (head == null);
    return true;
}


// check the size of the node
public int size() {
    return nodeCount;
}


// this is the peek method
public E stackTop() 
{
    if (head == null)
        throw new EmptyStackException();
    return head.getData();
}


// clear the Linked Stack
public void clear() {
    head = null;
    nodeCount = 0;
}

// convert to text
        public String toString() {
            String rtn = "";

            if (nodeCount == 0) {
                rtn += "<empty>";
            }
            else {
                Node<E> t = head;

                while (t != null){
                    /* return the node data on a line with the head node data
                     at the beginning of the line and the arrow pointing to 
                     each successive node*/
                    rtn += t.getData() + "->";
                    // go on to the next
                    t = t.getNext();
                }
            rtn += "null";
            }
            return rtn;

        }


        }

And the driver:

import java.util.Iterator;
import java.util.Scanner;

public class StackDriver<E> implements Iterator<E>{

/**
 * @param args
 */
public static void main(String[] args) {

//Initialize the driver
StackDriver run = new StackDriver();
run.doIt();

}
public void doIt() {

    // gather the input
    Scanner keyboard = new Scanner(System.in);
    System.out.println("Please enter a phrase. This program will verify" +
            " if the phrase is a palindrome.");

    // holder for the phrase
    String phrase;

    // holder for the reversed phrase
    String reversed = "";

    phrase = keyboard.nextLine().toUpperCase();
    System.out.println("You entered: "+ phrase);

    // create the two stacks for the characters
    LinkedStack<E> alpha = new LinkedStack<E>();
    LinkedStack<E> punctuation = new LinkedStack<E>();

    //------------------------------------------
        for(int i=0; i<phrase.length(); i++)
        {
        // if the character is a letter, push it onto the letters stack
            char c = phrase.charAt(i);
            if (true == Character.isLetter(c))

        {
            // (testing purposes only- remove next line)
                System.out.println("LETTER");
                String A = Character.toString(c);

            // push the letter onto the stack   
                alpha.push((E) new Node<E>());      
        }

        // else push it onto the characters stack
        else
        {
            // (testing purposes only- remove next line)
            System.out.println("NOT LETTER");
            String B = Character.toString(c);

            // push the character onto the stack
            punctuation.push((E) new String(B));    
        }
            // then pop the letters stack
        while (!alpha.isEmpty());   
        {
            reversed += alpha.pop();
        }
        }
        //------------------------------------------
    // if it equals the String phrase
        if (reversed == phrase)
            // it is a palindrome
            System.out.println("The phrase you entered is a palindrome");
    else
        System.out.println("The phrase you entered is NOT a palindrome");
        System.out.println("phrase: " + phrase);
        System.out.println("alpha: " + alpha);
        System.out.println("reversed: " + reversed);
}
@Override
public boolean hasNext() {
    // TODO Auto-generated method stub
    return true;
}
@Override
public E next() {
    // TODO Auto-generated method stub
    return null;
}
@Override
public void remove() {
    // TODO Auto-generated method stub

}


}

And the result:

Please enter a phrase. This program will verify if the phrase is a palindrome.
mom
You entered: MOM
LETTER
LETTER
LETTER
The phrase you entered is NOT a palindrome
phrase: MOM
alpha: <empty>
reversed: nullnullnull
2
  • try to show your problem with less code... Commented Feb 27, 2013 at 18:05
  • @Aubin: that would be great advice for someone who's not doing homework, or if it were a reproducible bug in someone else's library. But at the level that Mike Demers is currently programming, he shouldn't be expected to be capable of showing the problem with less code. Besides, if he knew what exact code to show, he'd also know where the problem was. Commented Feb 27, 2013 at 18:19

3 Answers 3

4

If I got your question properly, I think the issue is indeed your push method in the LinkedStack class. Take a look.

public void push(E data) {
    head = new Node<E>();
    nodeCount++;
}

You create a new Node, assign it to head and increment the number of nodes of your stack, but you never actually link the older head or populate the new current head, you just replace the head with a new node that has no previous or next element.

Sign up to request clarification or add additional context in comments.

2 Comments

I noticed this and was about to post, but decided to refresh first. Everytime he pushes he breaks of the linked list at head, and also does not store the data inside the not itself, so it does nothing.
@JesusAdoboLuzon Exactly! It's just an empty head node with no data but an accurate elementCount (i.e. The stack says he has 4 elements, but it has an empty head).
2
// A method to push the data onto a stack and increment the node count
public void push(E data) {
    head = new Node<E>();
    nodeCount++;
    }

This method is wrong. When you push a new node, you need to set it's next to the current head. You also need to populate that node with your data.

Comments

0

This may or may not be your whole problem, but it's definitely part of it...

// A method to push the data onto a stack and increment the node count
public void push(E data) {
    head = new Node<E>();
    nodeCount++;
}
  • always replaces head with a new node that contains no data, even though an object of E type was passed. You need to call head.setData(data).
  • you need to also add to the list rather than replace the head.
    if( head == null ) { head = new Node(); head.setData(data); } else { Node n = new Node(); n.setData(data); Node last = ...; // leaving getting the last node in the list as an exercise for the reader last.setNext(n); }

1 Comment

Thank you all for the help on this- this is what I needed to get moving again. I appreciate it!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.