Question

I am learning Stack today. I am trying to implement push(Element) method, but for some reasons it is not working.

I have added 10 items to my stack, then using toString method I print. The only item prints is my most Top Element. Your help would be greatly appreciated!.

private Node head = null;
private Node tail = null;
private static int size;

public void push(Customer custPair)
{
    if (head == null)
    {
        head = new Node(custPair, null);
        tail = head;
        size++;
    } else
    {
        tail.next = head;
        head = new Node(custPair, null);
        size++;
    }

}

@Override
public String toString()
{
    StringBuilder sBuilder = new StringBuilder();

    // Walk down the list and append all values
    Node curNode = head;
    while (curNode != null)
    {
        sBuilder.append(curNode.value.toString()).append("\n");
        curNode = curNode.next;
    }
    return sBuilder.toString();
}
Was it helpful?

Solution

Your logic is wrong when the stack already has a head. I think the new head must point to old head (via .next).

I'm bit confused, are you implementing a LIFO or FIFO stack?

For a LIFO

else {
    Node node = new Node(custPair, null);
    node.next = head;
    head = node;
    size++;
}

For a LIFO Stack, you really don't need a tail.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top