mirror of
https://github.com/trekhleb/javascript-algorithms.git
synced 2025-07-06 17:44:08 +08:00
Add comments to Stack code.
This commit is contained in:
@ -2,6 +2,9 @@ import LinkedList from '../linked-list/LinkedList';
|
|||||||
|
|
||||||
export default class Stack {
|
export default class Stack {
|
||||||
constructor() {
|
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();
|
this.linkedList = new LinkedList();
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -9,6 +12,7 @@ export default class Stack {
|
|||||||
* @return {boolean}
|
* @return {boolean}
|
||||||
*/
|
*/
|
||||||
isEmpty() {
|
isEmpty() {
|
||||||
|
// The queue is empty in case if its linked list don't have tail.
|
||||||
return !this.linkedList.tail;
|
return !this.linkedList.tail;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -17,9 +21,11 @@ export default class Stack {
|
|||||||
*/
|
*/
|
||||||
peek() {
|
peek() {
|
||||||
if (this.isEmpty()) {
|
if (this.isEmpty()) {
|
||||||
|
// If linked list is empty then there is nothing to peek from.
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Just read the value from the end of linked list without deleting it.
|
||||||
return this.linkedList.tail.value;
|
return this.linkedList.tail.value;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -27,6 +33,8 @@ export default class Stack {
|
|||||||
* @param {*} value
|
* @param {*} value
|
||||||
*/
|
*/
|
||||||
push(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);
|
this.linkedList.append(value);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -34,6 +42,8 @@ export default class Stack {
|
|||||||
* @return {*}
|
* @return {*}
|
||||||
*/
|
*/
|
||||||
pop() {
|
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();
|
const removedTail = this.linkedList.deleteTail();
|
||||||
return removedTail ? removedTail.value : null;
|
return removedTail ? removedTail.value : null;
|
||||||
}
|
}
|
||||||
|
Reference in New Issue
Block a user