[Queue] LinkedList로 구현하기
2020. 6. 3. 16:44ㆍ컴퓨터언어/자료구조&알고리즘
728x90
반응형
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Node { | |
constructor(value) { | |
this.value = value; | |
this.next = null; | |
} | |
} | |
class Queue { | |
constructor(){ | |
this.first = null; | |
this.last = null; | |
this.length = 0; | |
} | |
peek() { | |
return this.first | |
} | |
enqueue(value){ | |
const newNode = new Node(value); | |
if (!this.first) { | |
this.first = newNode; | |
} | |
const temp = this.last; | |
newNode.next = temp; | |
this.last = newNode; | |
this.length++; | |
return this | |
} | |
dequeue(){ | |
if (this.first === this.last) { | |
return "The queue is empty, cannot dequeue anything." | |
} | |
let currentNode = this.last; | |
let prevNode = this.last; | |
while(currentNode.next) { | |
if (!currentNode.next.next) { | |
prevNode = currentNode; | |
} | |
currentNode = currentNode.next; | |
} | |
prevNode.next = null; | |
this.first = prevNode; | |
this.length--; | |
return this | |
} | |
} | |
const myQueue = new Queue(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Node { | |
constructor(value) { | |
this.value = value; | |
this.next = null; | |
} | |
} | |
class Queue { | |
constructor(){ | |
this.first = null; | |
this.last = null; | |
this.length = 0; | |
} | |
peek() { | |
return this.first | |
} | |
enqueue(value){ | |
const newNode = new Node(value); | |
if (!this.first) { | |
this.first = newNode; | |
this.last = newNode; | |
} else { | |
this.last.next = newNode; | |
this.last = newNode; | |
} | |
this.length++; | |
return this | |
} | |
dequeue(){ | |
if (this.first === this.last) { | |
this.last = null | |
} | |
if (this.length === 0) { | |
return "The queue is empty, cannot remove anything." | |
} | |
// const target = this.first | |
this.first = this.first.next; | |
this.length--; | |
// return target | |
return this | |
} | |
//isEmpty; | |
} | |
const myQueue = new Queue(); |
728x90
반응형
'컴퓨터언어 > 자료구조&알고리즘' 카테고리의 다른 글
[Recursion] 팩토리얼 구현하기 (0) | 2020.06.04 |
---|---|
[Tree] JS로 구현하기 (0) | 2020.06.04 |
[Stack] Linked List로 구현하기 (0) | 2020.06.03 |
[Double Linked List] JS로 구현하기 (0) | 2020.05.28 |
[Linked List] JS로 구현하기 (0) | 2020.05.28 |