A coding challenge to write a function sortStack
that receives a stack of integers into ascending order (with largest integers on top) and returns another stack with sorted integers. At most one additional stack may be used to hold items; no other data structures may be used to copy or hold the elements.
Stack Class:
class Stack { constructor() { this.storage = []; } push(item) { this.storage.push(item); } pop() { return this.storage.pop(); } peek() { return this.storage[this.storage.length-1]; } isEmpty() { return this.storage.length === 0; } printContents() { this.storage.forEach(elem => console.log(elem)); } }
Stack:
const s = new Stack(); s.push(4); s.push(10); s.push(8); s.push(5); s.push(1); s.push(6);
My solution:
const sortStack = (stack) => { sorted = new Stack(); while (stack.storage.length) { tmp = stack.pop(); if (tmp >= sorted.peek()) { sorted.push(tmp); } else { while (tmp < sorted.peek()) { stack.push(sorted.pop()); } sorted.push(tmp); } } return sorted; } sortedStack = sortStack(s); sortedStack.printContents(); // correctly outputs 1, 4, 5, 6, 8, 10
This iterative solution returns the correct output on multiple test cases, and there are no missing edge cases or other logical flaws that I can see, however I don't like the nested while-loop.
I want to keep the solution iterative, so how could I go about not having to use the nested while-loop?
!stack.isEmpty()
instead ofstack.storage.length
?\$\endgroup\$