Advertisement
Guest User

Untitled

a guest
Jul 24th, 2019
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.86 KB | None | 0 0
  1. class Stack {
  2. constructor() {
  3. this.storage = [];
  4. }
  5.  
  6. push(item) {
  7. this.storage.push(item);
  8. }
  9.  
  10. pop() {
  11. return this.storage.pop();
  12. }
  13.  
  14. peek() {
  15. return this.storage[this.storage.length-1];
  16. }
  17.  
  18. isEmpty() {
  19. return this.storage.length === 0;
  20. }
  21.  
  22. printContents() {
  23. this.storage.forEach(elem => console.log(elem));
  24. }
  25. }
  26.  
  27. const s = new Stack();
  28. s.push(4);
  29. s.push(10);
  30. s.push(8);
  31. s.push(5);
  32. s.push(1);
  33. s.push(6);
  34.  
  35. const sortStack = (stack) => {
  36. sorted = new Stack();
  37. while (stack.storage.length) {
  38. tmp = stack.pop();
  39. if (tmp >= sorted.peek()) {
  40. sorted.push(tmp);
  41. } else {
  42. while (tmp < sorted.peek()) {
  43. stack.push(sorted.pop());
  44. }
  45. sorted.push(tmp);
  46. }
  47. }
  48. return sorted;
  49. }
  50.  
  51. sortedStack = sortStack(s);
  52. sortedStack.printContents(); // correctly outputs 1, 4, 5, 6, 8, 10
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement