Consider a stack implemented using a linked list. The following operations are performed in order:
- Push 10
- Push 20
- Pop
- Push 30
What is the printed state of the stack (top to bottom)?
class Node { public int data; public Node next; public Node(int d) { data = d; next = null; } } class Stack { private Node top; public void Push(int x) { Node newNode = new Node(x); newNode.next = top; top = newNode; } public int Pop() { if (top == null) throw new InvalidOperationException("Stack is empty"); int val = top.data; top = top.next; return val; } public void PrintStack() { Node temp = top; while (temp != null) { Console.Write(temp.data + " -> "); temp = temp.next; } Console.WriteLine("null"); } } Stack s = new Stack(); s.Push(10); s.Push(20); s.Pop(); s.Push(30); s.PrintStack();
Remember that push adds to the top and pop removes from the top.
After pushing 10 and 20, the stack is 20 -> 10 -> null. Popping removes 20, leaving 10. Pushing 30 adds it on top, so stack is 30 -> 10 -> null.
For a stack implemented using a linked list, what is the time complexity of the Push and Pop operations?
Think about where the top pointer is and how nodes are added or removed.
Both Push and Pop add or remove nodes at the head of the linked list, which takes 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?
public int Pop() {
int val = top.data;
top = top.next;
return val;
}Consider what happens if top is null and you try to access top.data.
If top is null, accessing top.data causes a NullReferenceException because you are dereferencing a null object.
Consider the following sequence of operations on a linked list stack:
- Push 5
- Push 15
- Push 25
- Pop
- Push 35
- Pop
What is the printed state of the stack (top to bottom)?
class Node { public int data; public Node next; public Node(int d) { data = d; next = null; } } class Stack { private Node top; public void Push(int x) { Node newNode = new Node(x); newNode.next = top; top = newNode; } public int Pop() { if (top == null) throw new InvalidOperationException("Stack is empty"); int val = top.data; top = top.next; return val; } public void PrintStack() { Node temp = top; while (temp != null) { Console.Write(temp.data + " -> "); temp = temp.next; } Console.WriteLine("null"); } } Stack s = new Stack(); s.Push(5); s.Push(15); s.Push(25); s.Pop(); s.Push(35); s.Pop(); s.PrintStack();
Trace each push and pop carefully, updating the top pointer.
Push 5: stack 5 -> null
Push 15: 15 -> 5 -> null
Push 25: 25 -> 15 -> 5 -> null
Pop removes 25: 15 -> 5 -> null
Push 35: 35 -> 15 -> 5 -> null
Pop removes 35: 15 -> 5 -> null
Which of the following is the best reason to choose a linked list over an array for implementing a stack?
Think about resizing arrays and memory allocation.
Linked lists can grow and shrink dynamically without needing to resize or copy elements, unlike arrays which may need resizing.
