[TS] Implement a singly linked list in TypeScript
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<T> { value: T next?: LinkedListNode<T> } /** * Linked list for items of type T */ export class LinkedList<T> { public head?: LinkedListNode<T> = undefined; public tail?: LinkedListNode<T> = 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<number>(); 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]); });
We can also see the beautiy of Generator with Array.from partten.
Array.from(list.values())
It saves lots of code to keep maintaing the indexing of the array.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2016-10-02 [Angular2 Router] Configure Auxiliary Routes in the Angular 2 Router - What is the Difference Towards a Primary Route?
2016-10-02 [NodeJS] Use Secrets When Deploying Applications with Now
2016-10-02 [Angular2 Router] Redirects and Path Matching - Avoid Common Routing Pitfall
2016-10-02 [Javascript] Safer property access with Lodash's 'get' method
2016-10-02 [CSS] Introduction to CSS Columns
2016-10-02 [Angular 2] Controlling Rx Subscriptions with Async Pipe and BehaviorSubjects
2016-10-02 [Javascript] Promise-based functions should not throw exceptions