TypeScript数据结构与算法(7)最基础的数据结构-链表队列-LinkedListQueue

使用链表来实现队列,源码如下:

import { Interface_Queue } from "../Interface_Queue";


class Node<T>{
    public e: T;
    public next: Node<T>;

    public constructor(e: T, next: Node<T>) {
        this.e = e;
        this.next = next;
    }

}


/**
* Autor: Created by 李清风 on 2020-12-19.
* Desc: 链表队列,关键词:从head端删除元素,从tail端插入元素
*/
export class DataStruct_LinkedListQueue<T> implements Interface_Queue<T> {

    private head: Node<T>;
    private tail: Node<T>; //尾指针概念

    private size: number;

    public constructor() {
        this.head = this.tail = null;  //初始化时,一个元素都没有
        this.size = 0;
    }

    getSize(): number {
        return this.size;
    }

    isEmpty(): boolean {
        return this.size == 0;
    }


    //入队,从队尾进行
    enqueue(e: T): void {
        if (this.tail == null) {
            this.tail = new Node(e, null);
            this.head = this.tail;
        } else {
            this.tail.next = new Node(e, null);
            this.tail = this.tail.next;
        }
        this.size++;
    }

    //出队,队首
    dequeue(): T {
        if (this.isEmpty()) {
            throw new Error("Cannot dequeue from an empty queue.");
        }
        let retNode = this.head;
        this.head = this.head.next;//将队首指针脱离
        retNode.next = null;
        if (this.head == null) { //如果此时head为空
            this.tail = null;
        }
        this.size--;
        return retNode.e;
    }

    getFront(): T {
        if (this.isEmpty()) {
            throw new Error("Cannot getFront from an empty queue.");
        }
        return this.head.e; //直接返回头部
    }

}

 

posted @ 2021-01-21 15:54  CYNLINQ  阅读(198)  评论(0)    收藏  举报