前边有一章介绍了 用两个栈实现一个队列 ,本文就介绍一下怎么 用链表实现队列 ?
一、思路 记录链表的 head 、 tail 入队,在 tail 位置入队 出队,在 head 位置出队 队列的 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 66 67 68 69 70 71 72 73 interface IListNode { value : number next : IListNode | null }class MyQueue { 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 } }const q = new MyQueue () q.add (100 ) q.add (200 ) q.add (300 )console .log (q.length )console .log (q.delete ())console .log (q.length )console .log (q.delete ())console .log (q.length )console .log (q.delete ())console .log (q.length )console .log (q.delete ())console .log (q.length )console .log (q.delete ())console .log (q.length )
三、性能测试 使用数组的 push 、shift 操作模拟队列,来对比用链表实现的队列,进行 10万次 入队、出队模拟测试。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 const q1 = new MyQueue ()console .time ('queue with list' )for (let i = 0 ; i < 10 * 10000 ; i++) { q1.add (i) }for (let i = 0 ; i < 10 * 10000 ; i++) { q1.delete () }console .timeEnd ('queue with list' )const q2 = []console .time ('queue with array' )for (let i = 0 ; i < 10 * 10000 ; i++) { q2.push (i) }for (let i = 0 ; i < 10 * 10000 ; i++) { q2.shift () }console .timeEnd ('queue with array' )
运行 queue with list run time: 0
queue with array run time: 0
通过运行得知 用数组模拟队列 的方法远不如 用链表实现队列 的方法的执行效率。
四、算法复杂度 空间复杂度都是 O(n) add 时间复杂度:链表 O(1) ; 数组 O(1) delete 时间复杂度:链表 O(1) ; 数组 O(n) 总结:数据量越大越能突显算法的重要性 。
《数据结构与算法》系列 什么是算法复杂度 堆(heap)、栈(stack)、队列(queue) 把一个数组旋转k步 判断字符串是否括号匹配 数组、栈、链表、队列结构与对比 用两个栈实现一个队列 反转单向链表 用链表实现队列 二分查找 查找两数之和 欢迎访问:天问博客