Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Stack<T> {
- private stack: T[];
- constructor(s: T[] = []) {
- this.stack = s;
- }
- push = (item: T) => this.stack.push(item);
- pop = (): T => {
- if (this.isEmpty())
- throw new Error("Stack Underflow!");
- return this.stack.pop()!;
- }
- top = (): T => {
- if (this.isEmpty())
- throw new Error("Stack is Empty!");
- return this.stack[this.stack.length - 1];
- }
- isEmpty = (): boolean => this.stack.length === 0;
- stringify = (): string => JSON.stringify(this.stack);
- }
- const insertAtBottom = <T>(s: Stack<T>, item: T): void => {
- if (s.isEmpty()) {
- s.push(item);
- return;
- }
- const top = s.pop();
- insertAtBottom(s, item);
- s.push(top);
- }
- const reverse = <T>(s: Stack<T>): void => {
- if (s.isEmpty())
- return;
- const top = s.pop();
- reverse(s);
- insertAtBottom(s, top);
- }
- const stack = new Stack<number>(([4, 2, 8, 3]));
- reverse(stack);
- console.log(stack.stringify());
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement