TypeScript实现数据结构(一)栈,队列,链表

35次阅读

共计 1792 个字符,预计需要花费 5 分钟才能阅读完成。

最近在学习 typescript,就想着用 typescript 自己练习一些基本的数据结构,记录一下,读者有什么想法和建议也可以交流一下。

class Stack<T>{
private items = null;
constructor() {
this.items = new Array<T>();
}
push(data: T): void {
this.items.push(data);
}
pop(): T {
return this.items.pop();
}
top(): T {
return this.items[this.items.length – 1];
}
isEmpty(): boolean {
return this.items.length === 0;
}
size(): number {
return this.items.length;
}
clear(): void {
this.items = new Array<T>();
}
print(): void {
console.log(this.items);
}
}

队列
class Queue<T>{
private items = null;
constructor() {
this.items = new Array<T>();
}
enqueue(data: T): void {
this.items.push(data);
}
dequeue(): T {
return this.items.shift();
}
head(): T {
return this.items[0];
}
size(): number {
return this.items.length;
}
clear(): void {
this.items = new Array<T>();
}
isEmpty(): boolean {
return this.items.length === 0;
}
tail(): T {
return this.items[this.items.length – 1];
}
print(): void {
console.log(this.items);
}
}

链表
class LinkNode<T>{
public data: T;
public next: LinkNode<T>;
constructor(data: T) {
this.data = data;
this.next = null;
}
}

class LinkList<T>{
private head: LinkNode<T>;
private tail: LinkNode<T>;
private length: number;
constructor(){
this.head = null;
this.tail = null;
this.length = 0;
}
append(data: T): void {
let newNode = new LinkNode<T>(data);
if (this.head === null) {
this.head = newNode;
this.tail = newNode;
} else {
this.tail.next = newNode;
this.tail = newNode.next;
}
this.length++;
}
print(): void{
let cur = this.head;
while(cur != null) {
console.log(cur.data);
cur = cur.next;
}
}
insert(index: number, data: T): void {
let newNode = new LinkNode<T>(data);
if (index === 0) {
// 头结点
newNode.next = this.head;
this.head = newNode;
this.length++;
} else if (index > 0 && index < this.length) {
// 中间节点
let cur = this.head;
for(let i = 1; i < index; i++) {
cur = cur.next;
}
newNode.next = cur.next;
cur.next = newNode;
this.length++;
} else if (index === this.length) {
// 尾节点
this.tail.next = newNode;
this.tail = newNode;
this.length++;
}
}
remove(index) : void {
if (index >= 0 && index < this.length) {
// 合法范围
let cur = this.head;
}

}
}

正文完
 0