mirror of
https://github.com/trekhleb/javascript-algorithms.git
synced 2025-12-19 08:59:05 +08:00
Add topological sorting.
This commit is contained in:
@@ -5,10 +5,16 @@ export default class Stack {
|
||||
this.linkedList = new LinkedList();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return {boolean}
|
||||
*/
|
||||
isEmpty() {
|
||||
return !this.linkedList.tail;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return {LinkedListNode}
|
||||
*/
|
||||
peek() {
|
||||
if (!this.linkedList.tail) {
|
||||
return null;
|
||||
@@ -17,15 +23,35 @@ export default class Stack {
|
||||
return this.linkedList.tail.value;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {*} value
|
||||
*/
|
||||
push(value) {
|
||||
this.linkedList.append(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return {LinkedListNode}
|
||||
*/
|
||||
pop() {
|
||||
const removedTail = this.linkedList.deleteTail();
|
||||
return removedTail ? removedTail.value : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return {*[]}
|
||||
*/
|
||||
toArray() {
|
||||
return this.linkedList
|
||||
.toArray()
|
||||
.map(linkedListNode => linkedListNode.value)
|
||||
.reverse();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {function} [callback]
|
||||
* @return {string}
|
||||
*/
|
||||
toString(callback) {
|
||||
return this.linkedList.toString(callback);
|
||||
}
|
||||
|
||||
@@ -62,4 +62,16 @@ describe('Stack', () => {
|
||||
expect(stack.pop().value).toBe('test2');
|
||||
expect(stack.pop().value).toBe('test1');
|
||||
});
|
||||
|
||||
it('should be possible to convert stack to array', () => {
|
||||
const stack = new Stack();
|
||||
|
||||
expect(stack.peek()).toBeNull();
|
||||
|
||||
stack.push(1);
|
||||
stack.push(2);
|
||||
stack.push(3);
|
||||
|
||||
expect(stack.toArray()).toEqual([3, 2, 1]);
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user