mirror of
https://github.com/trekhleb/javascript-algorithms.git
synced 2025-12-19 08:59:05 +08:00
Add Stack.
This commit is contained in:
1
src/data-structures/stack/README.md
Normal file
1
src/data-structures/stack/README.md
Normal file
@@ -0,0 +1 @@
|
||||
# Queue
|
||||
28
src/data-structures/stack/Stack.js
Normal file
28
src/data-structures/stack/Stack.js
Normal file
@@ -0,0 +1,28 @@
|
||||
import LinkedList from '../linked-list/LinkedList';
|
||||
|
||||
export default class Stack {
|
||||
constructor() {
|
||||
this.linkedList = new LinkedList();
|
||||
}
|
||||
|
||||
isEmpty() {
|
||||
return !this.linkedList.tail;
|
||||
}
|
||||
|
||||
peek() {
|
||||
if (!this.linkedList.tail) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return this.linkedList.tail.value;
|
||||
}
|
||||
|
||||
push(value) {
|
||||
this.linkedList.append({ value });
|
||||
}
|
||||
|
||||
pop() {
|
||||
const removedTail = this.linkedList.deleteTail();
|
||||
return removedTail ? removedTail.value : null;
|
||||
}
|
||||
}
|
||||
51
src/data-structures/stack/__test__/Stack.test.js
Normal file
51
src/data-structures/stack/__test__/Stack.test.js
Normal file
@@ -0,0 +1,51 @@
|
||||
import Stack from '../Stack';
|
||||
|
||||
describe('Stack', () => {
|
||||
it('should create empty stack', () => {
|
||||
const stack = new Stack();
|
||||
expect(stack).not.toBeNull();
|
||||
expect(stack.linkedList).not.toBeNull();
|
||||
});
|
||||
|
||||
it('should stack data to stack', () => {
|
||||
const stack = new Stack();
|
||||
|
||||
stack.push(1);
|
||||
stack.push(2);
|
||||
|
||||
expect(stack.linkedList.toString()).toBe('1,2');
|
||||
});
|
||||
|
||||
it('should peek data from stack', () => {
|
||||
const stack = new Stack();
|
||||
|
||||
expect(stack.peek()).toBeNull();
|
||||
|
||||
stack.push(1);
|
||||
stack.push(2);
|
||||
|
||||
expect(stack.peek()).toBe(2);
|
||||
expect(stack.peek()).toBe(2);
|
||||
});
|
||||
|
||||
it('should check if stack is empty', () => {
|
||||
const stack = new Stack();
|
||||
|
||||
expect(stack.isEmpty()).toBeTruthy();
|
||||
|
||||
stack.push(1);
|
||||
|
||||
expect(stack.isEmpty()).toBeFalsy();
|
||||
});
|
||||
|
||||
it('should pop data from stack', () => {
|
||||
const stack = new Stack();
|
||||
|
||||
stack.push(1);
|
||||
stack.push(2);
|
||||
|
||||
expect(stack.pop()).toBe(2);
|
||||
expect(stack.pop()).toBe(1);
|
||||
expect(stack.isEmpty()).toBeTruthy();
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user