如果您沒有信心或想了解更多關於鍊錶及其類型以及我們如何對其進行操作,請參閱我的另一篇有關單鍊錶和雙鍊錶的文章
使用 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中文網其他相關文章!