function Stack() {
this.top = null;
this.size = 0;
}
function Node(data) {
this.data = data;
this.next = null;
}
Stack.prototype.push = function(data) {
const node = new Node(data);
node.next = this.top;
this.top = node;
this.size++;
};
Stack.prototype.pop = function() {
if (this.top === null) return;
const data = this.top.data;
this.top = this.top.next;
this.size = Math.max(0, this.size - 1);
return data;
};
Stack.prototype.peek = function() {
if (!this.top) return;
return this.top.data;
};
Stack.prototype.isEmpty = function() {
return this.size === 0 && !this.top;
};
Stack.prototype.sort = function() {
const temp = new Stack();
while (!this.isEmpty()) {
const item = this.pop();
while (!temp.isEmpty() && temp.peek() > item) {
this.push(temp.pop());
}
temp.push(item);
}
while (!temp.isEmpty()) {
this.push(temp.pop());
}
};