Browse Source

完成list列表

master
blobt 4 years ago
parent
commit
048bfd3e4d
  1. 167
      src/List.ts

167
src/List.ts

@ -0,0 +1,167 @@
import { ListNode } from "./ListNode";
export class List<T>{
private _headNode: ListNode<T>;
private _length: number;
public constructor() {
this._headNode = new ListNode<T>();
this._headNode.next = this._headNode;
this._headNode.prev = this._headNode;
this._length = 0; //头节点不计算
}
/**
*
* @returns
*/
public empty(): boolean {
return this._headNode.next === this._headNode;
}
/**
*
*/
public get length(): number {
return this._length;
}
/**
* c++
* @returns
*/
public begin(): ListNode<T> {
if (this._headNode.next === null) {
throw new Error("头节点不能为null");
}
return this._headNode.next;
}
/**
*
* @returns c++
*/
public end(): ListNode<T> {
return this._headNode;
}
/**
*
* @param data
* @returns
*/
public contains(data: T): boolean {
for (let link: ListNode<T> | null = this._headNode.next; link !== null && link != this._headNode; link = link.next) {
if (link !== null) {
if (link.data !== undefined) {
if (data === link.data) {
return true;
}
}
}
}
return false;
}
/**
*
* @param cb
*/
public forNext(cb: (data: T) => void): void {
for (let link: ListNode<T> | null = this._headNode.next; link !== null && link !== this._headNode; link = link.next) {
if (link.data !== undefined) {
cb(link.data);
}
}
}
/**
*
* @param cb
*/
public forPrev(cb: (data: T) => void): void {
for (let link: ListNode<T> | null = this._headNode.next; link !== null && link !== this._headNode; link = link.prev) {
if (link.data !== undefined) {
cb(link.data);
}
}
}
/**
*
* @param node
* @param data
* @returns
*/
public insertBefore(node: ListNode<T>, data: T): ListNode<T> {
let ret: ListNode<T> = new ListNode<T>(data);
ret.next = node;
ret.prev = node.prev;
if (node.prev !== null) {
node.prev.next = ret;
}
node.prev = ret;
this._length++;
return ret;
}
/**
*
* @param node
*/
public remove(node: ListNode<T>): void {
let next: ListNode<T> | null = node.next;
let prev: ListNode<T> | null = node.prev;
if (prev !== null) {
prev.next = next;
}
if (next !== null) {
next.prev = prev;
}
this._length--;
}
/**
*
* @param data
*/
public push(data: T): void {
this.insertBefore(this.end(), data);
}
/**
*
* @returns
*/
public pop(): T | undefined {
let ret: T | undefined = undefined;
let prev: ListNode<T> | null = this.end().prev;
if (prev !== null) {
ret = prev.data;
this.remove(prev);
}
return ret;
}
/**
*
* @param data
*/
public push_fornt(data: T): void {
this.insertBefore(this.begin(), data);
}
/**
*
* @returns
*/
public pop_front(): T | undefined {
let ret: T | undefined = undefined;
ret = this.begin().data;
this.remove(this.begin());
return ret;
}
}
Loading…
Cancel
Save