mirror of
https://github.moeyy.xyz/https://github.com/trekhleb/javascript-algorithms.git
synced 2024-12-25 22:46:20 +08:00
Add comments to Stack code.
This commit is contained in:
parent
571d9312cd
commit
20b0c48e84
@ -2,6 +2,9 @@ import LinkedList from '../linked-list/LinkedList';
|
||||
|
||||
export default class Stack {
|
||||
constructor() {
|
||||
// We're going to implement Queue based on LinkedList since this
|
||||
// structures a quite similar. Compare push/pop operations of the Stack
|
||||
// with append/deleteTail operations of LinkedList.
|
||||
this.linkedList = new LinkedList();
|
||||
}
|
||||
|
||||
@ -9,6 +12,7 @@ export default class Stack {
|
||||
* @return {boolean}
|
||||
*/
|
||||
isEmpty() {
|
||||
// The queue is empty in case if its linked list don't have tail.
|
||||
return !this.linkedList.tail;
|
||||
}
|
||||
|
||||
@ -17,9 +21,11 @@ export default class Stack {
|
||||
*/
|
||||
peek() {
|
||||
if (this.isEmpty()) {
|
||||
// If linked list is empty then there is nothing to peek from.
|
||||
return null;
|
||||
}
|
||||
|
||||
// Just read the value from the end of linked list without deleting it.
|
||||
return this.linkedList.tail.value;
|
||||
}
|
||||
|
||||
@ -27,6 +33,8 @@ export default class Stack {
|
||||
* @param {*} value
|
||||
*/
|
||||
push(value) {
|
||||
// Pushing means to lay the value on top of the stack. Therefore let's just add
|
||||
// new value at the end of the linked list.
|
||||
this.linkedList.append(value);
|
||||
}
|
||||
|
||||
@ -34,6 +42,8 @@ export default class Stack {
|
||||
* @return {*}
|
||||
*/
|
||||
pop() {
|
||||
// Let's try to delete the last node from linked list (the tail).
|
||||
// If there is no tail in linked list (it is empty) just return null.
|
||||
const removedTail = this.linkedList.deleteTail();
|
||||
return removedTail ? removedTail.value : null;
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user