Consider a stack implemented using a linked list. The following operations are performed in order:
- push(10)
- push(20)
- pop()
- push(30)
- peek()
What is the printed output of the peek() operation?
class Node { int data; Node next; Node(int data) { this.data = data; this.next = null; } } class Stack { Node top; void push(int x) { Node newNode = new Node(x); newNode.next = top; top = newNode; } int pop() { if (top == null) return -1; int val = top.data; top = top.next; return val; } int peek() { if (top == null) return -1; return top.data; } } public class Main { public static void main(String[] args) { Stack s = new Stack(); s.push(10); s.push(20); s.pop(); s.push(30); System.out.println(s.peek()); } }
Remember that pop() removes the top element, and peek() shows the current top.
After pushing 10 and 20, the stack top is 20. Popping removes 20, so top becomes 10. Then pushing 30 makes top 30. So peek() returns 30.
For a stack implemented using a linked list, what is the time complexity of the push and pop operations?
Think about how many nodes you need to traverse for push and pop.
Both push and pop operate only at the top node, so they take constant time O(1).
Given the following pop method in a linked list stack, what error will occur if pop() is called on an empty stack?
int pop() {
int val = top.data;
top = top.next;
return val;
}What happens if top is null and you try to access top.data?
If top is null, accessing top.data causes a NullPointerException.
Consider a linked list stack initially empty. Perform these operations:
- push(5)
- push(15)
- push(25)
- pop()
- push(35)
What is the printed stack content from top to bottom?
class Node { int data; Node next; Node(int data) { this.data = data; this.next = null; } } class Stack { Node top; void push(int x) { Node newNode = new Node(x); newNode.next = top; top = newNode; } int pop() { if (top == null) return -1; int val = top.data; top = top.next; return val; } void printStack() { Node curr = top; while (curr != null) { System.out.print(curr.data + " -> "); curr = curr.next; } System.out.println("null"); } } public class Main { public static void main(String[] args) { Stack s = new Stack(); s.push(5); s.push(15); s.push(25); s.pop(); s.push(35); s.printStack(); } }
Remember that pop() removes the top element, and push() adds on top.
After pushing 5, 15, 25, the stack is 25 -> 15 -> 5. Popping removes 25, so stack is 15 -> 5. Pushing 35 adds it on top: 35 -> 15 -> 5.
Which of the following is the best reason to use a linked list to implement a stack instead of an array?
Think about resizing arrays and memory allocation.
Linked lists grow dynamically without needing to resize, unlike arrays which may need costly resizing.
