TS实现栈

定义栈的接口

IStack.ts

// 定义栈的结构
interface IStack<T> {
    push(item: T): void;
    pop(): T | undefined;
    peek(): T | undefined;
    isEmpty(): boolean;
    size(): number;
}

export default IStack

使用数组实现栈

import IStack from "./IStack";

// 封装一个栈
class ArrayStack<T = any> implements IStack<T> {
    // 定义一个数组用于存储栈元素
    private arr: T[];
    constructor() {
        this.arr = []
    }
    push(item: T) {
        this.arr.push(item)
    }
    pop(): T | undefined {
        return this.arr.pop()
    }
    peek(): T | undefined {
        return this.arr[this.arr.length - 1]
    }
    isEmpty(): boolean  {
        return this.arr.length === 0 
    }
    size(): number {
        return this.arr.length
    }
}

export default ArrayStack

使用链表实现栈

import IStack from "./IStack";

// 封装一个栈
class LinkedStack<T = any> implements IStack<T> {
    push(item: T): void {
        throw new Error("Method not implemented.");
    }
    pop(): T | undefined {
        throw new Error("Method not implemented.");
    }
    peek(): T | undefined {
        throw new Error("Method not implemented.");
    }
    isEmpty(): boolean {
        throw new Error("Method not implemented.");
    }
    size(): number {
        throw new Error("Method not implemented.");
    }
}

// 创建栈实例
const stack = new LinkedStack<String>();

export default LinkedStack

实例

十进制转二进制

import ArrayStack from "./02_实现栈结构Stack(重构)";

function decimaToBinary(value: number): number {
    const sc = new ArrayStack();
    while (value > 0) {
        sc.push(value % 2);
        value = Math.floor(value / 2);
    }
    let res: string = '';
    while (!sc.isEmpty()) {
        res += sc.pop();
    }
    return Number(res);
}

console.log(decimaToBinary(10));
console.log(decimaToBinary(35));

输出

1010
100011

有效的括号

去往LeetCode: 有效的括号

import ArrayStack from "./02_实现栈结构Stack(重构)";

function ValidBracket(val: String) {
    const stack = new ArrayStack();
    let arr: string[] = []
    for(let i=0; i<val.length;i++) {
        let s = val.charAt(i);
        if(s==="("){
            stack.push(")")
        } else if(s==="{"){
            stack.push("}")
        } else if(s==="["){
            stack.push("]")
        } else {
            if(s!==stack.pop()) return false
        }
    }
    return stack.isEmpty()
}

console.log(ValidBracket("(()){}{}"))
console.log(ValidBracket("(()){}{}{"))
console.log(ValidBracket("(())}{}"))

输出结果:

true
false
false