X382: LinkedStackToString

For the question below, assume the following implementation of LinkedStack:

x
 
1
public class LinkedStack<T> implements StackInterface<T> {
2
    private Node<T> topNode;
3
    private int numberOfEntries;
4
5
    public LinkedStack() {
6
        this.topNode = null;
7
        numberOfEntries = 0;
8
    }// end default constructor
9
10
    @Override
11
    public void push(T newEntry) {
12
        topNode = new Node<T>(newEntry, topNode);
13
        numberOfEntries++;
14
    }
15
16
17
    @Override
18
    public T peek() {
19
        if (isEmpty()) {
20
            throw new EmptyStackException();
21
        }
22
        else {
23
            return (T)topNode.getData();
24
        }
25
    }// end peek
26
27
28
    @Override
29
    public T pop() {
30
        T top = peek();
31
        topNode = topNode.getNext();
32
        numberOfEntries--;
33
        return top;
34
    }
35
36
37
    @Override
38
    public boolean isEmpty() {
39
        return topNode == null;
40
    }
41
42
43
    @Override
44
    public void clear() {
45
        topNode = null;
46
    }
47
} // end LinkedStack
48
49
    public class Node<E> {
50
        private E data; // Entry in bag
51
        private Node<E> next; // Link to next node
52
53
        public Node(E dataPortion) {
54
            this(dataPortion, null);
55
        } // end constructor
56
57
58
        public Node(E dataPortion, Node<E> nextNode) {
59
            data = dataPortion;
60
            next = nextNode;
61
        } // end constructor
62
63
64
        public E getData() {
65
            if (data != null) {
66
                return data;
67
            }
68
            return null;
69
        }
70
71
72
        public Node<E> getNext() {
73
            return next;
74
        }
75
76
77
        public void setNext(Node<E> newNext) {
78
            next = newNext;
79
        }
80
    } // end Node

Below, you'll see most of a toString method implemented but a piece is missing. Currently the while loop will run infinitely. Add in the code to finish this method and the while loop will terminate when it is supposed to.

Your Answer:

xxxxxxxxxx
14
 
1
@SuppressWarnings("unchecked")
2
public String toString() {
3
    // find the top item in the stack
4
    Node<T> currentNode = topNode;
5
    String s = "";
6
    // loop through the whole stack.
7
    while (currentNode != null) {
8
        s = s + (String)currentNode.getData();
9
        //Add code
10
        
11
    }
12
    return s;
13
}
14
Reset

Practice a different Java exercise

Feedback

Your feedback will appear here when you check your answer.