0%
题目如下
补充
- 数组是连续存储,push很快,shift很慢
- 链表是非连续存储,add和delete都很快(但查找很慢)
- 链表实现队列要更快
思路如下
- 单向链表,但要同时记录head和tail
- 要从tail入队,从head出队,否则出队时tail不好定位
- length要实时记录,不可遍历链表获取
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
|
interface IListNode { value: number; next: IListNode | null; }
export class ListToQueue { private head: IListNode | null = null; private tail: IListNode | null = null; private len = 0 add(n:number) { const newNode: IListNode = { value:n, next:null } if(this.head == null){ this.head = newNode } const tailNode = this.tail if(tailNode){ tailNode.next = newNode } this.tail = newNode this.len++ } delete():number | null { const headNode = this.head if(headNode == null) return null if(this.len <= 0) return null const value = headNode.value this.head = headNode.next this.len-- return value } get length():number { return this.len } }
|
单元测试
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
|
import { ListToQueue } from './queue-with-list'
describe('链表实现队列', () => { it('add and length', () => { const q = new ListToQueue() expect(q.length).toBe(0)
q.add(100) q.add(200) q.add(300) expect(q.length).toBe(3) }) it('delete', () => { const q = new ListToQueue() expect(q.delete()).toBeNull()
q.add(100) q.add(200) q.add(300) expect(q.delete()).toBe(100) expect(q.delete()).toBe(200) expect(q.delete()).toBe(300) expect(q.delete()).toBeNull() }) })
|