如果您没有信心或想了解更多关于链表及其类型以及我们如何对其进行操作,请参阅我的另一篇有关单链表和双链表的文章
使用 Javascript 处理单链表和双链表的所有操作:- 最后一站解决方案
如果您有任何疑问,请随时联系我
享受代码,快乐编码。
class Node { constructor(value) { this.value = value; this.next = null; } } class LinkedList { constructor() { this.head = this.tail = null; this.size = 0; } append(value){ const newNode = new Node(value); if (this.head === null) { this.head = this.tail = newNode; this.size = 1; return ; } let currentNode = this.head; const pos = this.size-1; let counter = 0; while (currentNode) { if (counter++ === pos) { currentNode.next = newNode; this.tail = newNode; this.size++; break; } currentNode = currentNode.next; } } deleteFromHead() { if (this.head === null) { return ; } let currentNode = this.head; this.head = currentNode.next; this.size--; return this.head.value; } traversal() { let currentNode = this.head; while (currentNode) { console.log(currentNode.value); currentNode = currentNode.next; } } reverse(){ let currentNode = this.head; let nextNode = null; let prevNode = null; while(currentNode) { nextNode = currentNode.next; currentNode.next = prevNode; if (prevNode === null) { this.tail = prevNode; } prevNode = currentNode; currentNode = nextNode; } this.head = prevNode; this.traversal(); } } class Queue{ queue; constructor() { this.queue = new LinkedList(); } push(value) { this.queue.append(value) } pop() { this.queue.deleteFromHead(); } peak() { console.log(this.queue.head.value) } traversal() { this.queue.traversal() } reverse() { this.queue.reverse(); } } const q = new Queue(); q.push(20); q.push(13); q.push(3); q.push(5); q.push(9); q.pop() console.log(q); q.traversal() console.log('---------------Peak--------------') q.peak() console.log('-------------After Reverse ---------------'); q.reverse() /* Queue { queue: LinkedList { tail: Node { value: 9, next: null }, head: Node { value: 13, next: [Node] }, size: 4 } } 13 3 5 9 ---------------Peak-------------- 13 -------------After Reverse --------------- 9 5 3 13 */
以上是使用Javascript实现队列(链表)的详细内容。更多信息请关注PHP中文网其他相关文章!