博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[TS] Implement a singly linked list in TypeScript
阅读量:5795 次
发布时间:2019-06-18

本文共 1893 字,大约阅读时间需要 6 分钟。

In a singly linked list each node in the list stores the contents of the node and a reference (or pointer in some languages) to the next node in the list. It is one of the simplest way to store a collection of items.

In this lesson we cover how to create a linked list data structure and how to use its strengths to implement an O(1) FIFO queue.

 

/** * Linked list node */export interface LinkedListNode
{ value: T next?: LinkedListNode
}/** * Linked list for items of type T */export class LinkedList
{ public head?: LinkedListNode
= undefined; public tail?: LinkedListNode
= undefined; /** * Adds an item in O(1) **/ add(value: T) { const node = { value, next: undefined } if (!this.head) { this.head = node; } if (this.tail) { this.tail.next = node; } this.tail = node; } /** * FIFO removal in O(1) */ dequeue(): T | undefined { if (this.head) { const value = this.head.value; this.head = this.head.next; if (!this.head) { this.tail = undefined; } return value; } } /** * Returns an iterator over the values */ *values() { let current = this.head; while (current) { yield current.value; current = current.next; } }}

 

import { LinkedList } from './linkedList';test('basic', () => {  const list = new LinkedList
(); list.add(1); list.add(10); list.add(5); expect(Array.from(list.values())).toMatchObject([1, 10, 5]); expect(list.dequeue()).toBe(1); expect(Array.from(list.values())).toMatchObject([10, 5]); expect(list.dequeue()).toBe(10); expect(list.dequeue()).toBe(5); expect(list.dequeue()).toBe(undefined); expect(Array.from(list.values())).toMatchObject([]); list.add(5); expect(Array.from(list.values())).toMatchObject([5]);});

 

转载地址:http://hrffx.baihongyu.com/

你可能感兴趣的文章
测试色差脚本
查看>>
PHP cURL快速入门
查看>>
安卓 引导页实现(第一次登陆)
查看>>
struts2文件上传/下载(附源代码)
查看>>
(5)ionic2--导航
查看>>
C-Lodop打印页面
查看>>
1:SpringCloud概述 分布式介绍
查看>>
Qt项目配置构建路径
查看>>
kotlin避免判空语句
查看>>
grunt使用初步
查看>>
Java NIO 使用实例
查看>>
spring配置 Freemarker自定义标签
查看>>
Oracle 存储过程直接使用
查看>>
衣橱管家
查看>>
消息中间件(1)-JMS规范
查看>>
cygwin ctrl+s的问题
查看>>
python 中range和xrange的区别
查看>>
java并发编程(十五): Java内存模型
查看>>
mac osx 10.11 添加openssl头文件
查看>>
nginx and apache https 配置
查看>>