Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to declare the top node of the stack.
DSA Java
private Node [1];Attempts:
3 left
💡 Hint
Common Mistakes
Using 'head' or 'root' which are more common in linked lists but not typical for stack top.
Using variable names that do not clearly indicate the stack's top.
✗ Incorrect
The top of the stack is usually referenced by a variable named 'top' in linked list stack implementations.
2fill in blank
mediumComplete the push method to add a new node at the top of the stack.
DSA Java
public void push(int data) {
Node newNode = new Node(data);
newNode.next = [1];
top = newNode;
}Attempts:
3 left
💡 Hint
Common Mistakes
Setting newNode.next to null, which breaks the chain.
Assigning newNode.next to newNode itself, causing a cycle.
✗ Incorrect
The new node's next should point to the current top node before updating top to newNode.
3fill in blank
hardFix the error in the pop method to correctly remove and return the top element.
DSA Java
public int pop() {
if (top == null) {
throw new EmptyStackException();
}
int value = top.data;
top = [1];
return value;
}Attempts:
3 left
💡 Hint
Common Mistakes
Setting top to itself, causing no removal.
Setting top to null always, which empties the stack incorrectly.
✗ Incorrect
To remove the top node, update top to point to the next node in the stack.
4fill in blank
hardFill both blanks to check if the stack is empty and return the correct boolean.
DSA Java
public boolean isEmpty() {
return [1] == [2];
}Attempts:
3 left
💡 Hint
Common Mistakes
Comparing head or size which are not used here.
Using incorrect comparison operators.
✗ Incorrect
The stack is empty if the top node is null.
5fill in blank
hardFill all three blanks to implement the peek method that returns the top element without removing it.
DSA Java
public int peek() {
if ([1] == [2]) {
throw new EmptyStackException();
}
return [3].data;
}Attempts:
3 left
💡 Hint
Common Mistakes
Using head instead of top.
Returning data after removing the node.
✗ Incorrect
Peek checks if top is null to throw exception, then returns top.data without removing it.
