artenson.art98
artenson.art98

Reputation: 1605

How to write a print function for custom stack class in Java?

I'm want to write my own stack class and this is what I've written so far:

 public class Stack {

        private static class Node {
            private int data;
            private Node next;

            Node(int data) {
                this.data = data;
            }
        }

        Node top;

        public void push(int data) {
            Node node = new Node(data);
            if (top == null) {
                top = node;
                node.next = null;
                System.out.println(node);
            }
            node.next = top;
            top = node;
        }

        public void print() {...} // Help in completing this

    }

I've written others functions like peek and pop. But I need help in writing a print function that will print the elements of the stack without deleting them.

This is what I tried:

public void print() {
    Node node = top;
    while(node.next != null) {
        System.out.print(node.data + "  ");
        node = node.next;
    }
}

But I'm getting an endless loop. It is printing all the elements but the last element is being printed infinitely. And I also think that the first line of the print function Node node = top; will create some problem, will it? I think it has to do something with referencing. top and node refers to the same memory location, am I right? Please tell me will it create a problem? Or is it correct?

Upvotes: 0

Views: 244

Answers (1)

fgb
fgb

Reputation: 18569

The code in print is wrong. There the last two statements should be in an else block. There are 2 cases, when top is already set, and when it isn't. If both cases are run together, then they create a cycle in the list which will create an infinite loop when you try to print the stack.

This:

Node node = new Node(data);

Creates a new node and points node to this node. If top is null, then:

if (top == null) {
    top = node;
    node.next = null;
}

Sets top to point to this node, so node and top point to the same node.

Then:

node.next = top;

Sets next on this one node to point back to itself, because node and top are the same.

Upvotes: 1

Related Questions