I came across this solution for stack implementation using Linked List on Leetcode and I understood almost all the logic behind it except the min part. Can anyone please explain how the code is keep tracking of the minimum element after the first minimum element is popped?
Code
class MinStack {
private Node head;
public void push(int x) {
if (head == null)
head = new Node(x, x, null);
else
head = new Node(x, Math.min(x, head.min), head);
}
public void pop() {
head = head.next;
}
public int top() {
return head.val;
}
public int getMin() {
return head.min;
}
private class Node {
int val;
int min;
Node next;
private Node(int val, int min, Node next) {
this.val = val;
this.min = min;
this.next = next;
}
}
}
0and increments from there, so the minimum will always be0.