fueanta

Reverse Stack using Recursion

Jul 3rd, 2021
1,524
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class Stack<T> {
  2.     private stack: T[];
  3.  
  4.     constructor(s: T[] = []) {
  5.         this.stack = s;
  6.     }
  7.  
  8.     push = (item: T) => this.stack.push(item);
  9.  
  10.     pop = (): T => {
  11.         if (this.isEmpty())
  12.             throw new Error("Stack Underflow!");
  13.  
  14.         return this.stack.pop()!;
  15.     }
  16.  
  17.     top = (): T => {
  18.         if (this.isEmpty())
  19.             throw new Error("Stack is Empty!");
  20.  
  21.         return this.stack[this.stack.length - 1];
  22.     }
  23.  
  24.     isEmpty = (): boolean => this.stack.length === 0;
  25.  
  26.     stringify = (): string => JSON.stringify(this.stack);
  27. }
  28.  
  29. const insertAtBottom = <T>(s: Stack<T>, item: T): void => {
  30.     if (s.isEmpty()) {
  31.         s.push(item);
  32.         return;
  33.     }
  34.  
  35.     const top = s.pop();
  36.     insertAtBottom(s, item);
  37.     s.push(top);
  38. }
  39.  
  40. const reverse = <T>(s: Stack<T>): void => {
  41.     if (s.isEmpty())
  42.         return;
  43.  
  44.     const top = s.pop();
  45.     reverse(s);
  46.     insertAtBottom(s, top);
  47. }
  48.  
  49. const stack = new Stack<number>(([4, 2, 8, 3]));
  50. reverse(stack);
  51. console.log(stack.stringify());
  52.  
RAW Paste Data