mirror of
				https://github.com/krahets/hello-algo.git
				synced 2025-11-04 06:07:20 +08:00 
			
		
		
		
	feat: add linkedlist_stack in ts to doc
This commit is contained in:
		@ -396,7 +396,62 @@ comments: true
 | 
			
		||||
=== "TypeScript"
 | 
			
		||||
 | 
			
		||||
    ```typescript title="linkedlist_stack.ts"
 | 
			
		||||
    class LinkedListStack {
 | 
			
		||||
        private stackPeek: ListNode | null;  // 将头结点作为栈顶
 | 
			
		||||
        private stkSize: number = 0;   // 栈的长度
 | 
			
		||||
 | 
			
		||||
        constructor() {
 | 
			
		||||
            this.stackPeek = null;
 | 
			
		||||
        }
 | 
			
		||||
 | 
			
		||||
        /* 获取栈的长度 */
 | 
			
		||||
        get size(): number {
 | 
			
		||||
            return this.stkSize;
 | 
			
		||||
        }
 | 
			
		||||
 | 
			
		||||
        /* 判断栈是否为空 */
 | 
			
		||||
        isEmpty(): boolean {
 | 
			
		||||
            return this.size == 0;
 | 
			
		||||
        }
 | 
			
		||||
 | 
			
		||||
        /* 入栈 */
 | 
			
		||||
        push(num: number): void {
 | 
			
		||||
            const node = new ListNode(num);
 | 
			
		||||
            node.next = this.stackPeek;
 | 
			
		||||
            this.stackPeek = node;
 | 
			
		||||
            this.stkSize++;
 | 
			
		||||
        }
 | 
			
		||||
 | 
			
		||||
        /* 出栈 */
 | 
			
		||||
        pop(): number {
 | 
			
		||||
            const num = this.peek();
 | 
			
		||||
            if (!this.stackPeek) {
 | 
			
		||||
                throw new Error("栈为空!");
 | 
			
		||||
            }
 | 
			
		||||
            this.stackPeek = this.stackPeek.next;
 | 
			
		||||
            this.stkSize--;
 | 
			
		||||
            return num;
 | 
			
		||||
        }
 | 
			
		||||
 | 
			
		||||
        /* 访问栈顶元素 */
 | 
			
		||||
        peek(): number {
 | 
			
		||||
            if (!this.stackPeek) {
 | 
			
		||||
                throw new Error("栈为空!");
 | 
			
		||||
            }
 | 
			
		||||
            return this.stackPeek.val;
 | 
			
		||||
        }
 | 
			
		||||
 | 
			
		||||
        /* 将 List 转化为 Array 并返回 */
 | 
			
		||||
        toArray(): number[] {
 | 
			
		||||
            let node = this.stackPeek;
 | 
			
		||||
            const res = new Array<number>(this.size);
 | 
			
		||||
            for (let i = res.length - 1; i >= 0; i--) {
 | 
			
		||||
                res[i] = node!.val;
 | 
			
		||||
                node = node!.next;
 | 
			
		||||
            }
 | 
			
		||||
            return res;
 | 
			
		||||
        }
 | 
			
		||||
    }
 | 
			
		||||
    ```
 | 
			
		||||
 | 
			
		||||
=== "C"
 | 
			
		||||
 | 
			
		||||
		Reference in New Issue
	
	Block a user