Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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));
- }
- }
- const s = new Stack();
- s.push(4);
- s.push(10);
- s.push(8);
- s.push(5);
- s.push(1);
- s.push(6);
- 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
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement