Browse Source

实现队列和栈

master
blobt 4 years ago
parent
commit
f68877a590
  1. 41
      src/AdapterBase.ts
  2. 8
      src/IAdapter.ts
  3. 17
      src/Queue.ts
  4. 11
      src/Stack.ts

41
src/AdapterBase.ts

@ -0,0 +1,41 @@
import { IAdapter } from "./IAdapter";
import { List } from "./List";
export abstract class AdapterBase<T> implements IAdapter<T> {
protected _arr: Array<T> | List<T>;
constructor(useList: boolean = true) {
if (useList) {
this._arr = new List<T>();
} else {
this._arr = new Array<T>();
}
}
public add(t: T): void {
this._arr.push(t);
}
/**
*
*/
public abstract remove(): T | undefined;
public get length(): number {
return this._arr.length;
}
public get isEmpty(): boolean {
return this._arr.length <= 0;
}
clear(): void {
if(this._arr instanceof List){
this._arr = new List<T>();
} else {
this._arr = new Array<T>();
}
}
}

8
src/IAdapter.ts

@ -0,0 +1,8 @@
export interface IAdapter<T> {
add(t: T): void;
remove(): T | undefined;
clear(): void;
//属性
length: number;
isEmpty: boolean;
}

17
src/Queue.ts

@ -0,0 +1,17 @@
import { AdapterBase } from "./AdapterBase";
import { List } from "./List";
export class Quene<T> extends AdapterBase<T>{
public remove(): T | undefined {
if (this._arr.length > 0) {
if (this._arr instanceof List) {
return this._arr.pop_front();
} else {
return this._arr.shift();
}
} else {
return undefined;
}
}
}

11
src/Stack.ts

@ -0,0 +1,11 @@
import { AdapterBase } from "./AdapterBase";
export class Stack<T> extends AdapterBase<T>{
public remove(): T | undefined {
if(this._arr.length > 0){
this._arr.pop();
}
return undefined;
}
}
Loading…
Cancel
Save