Add Stack.

This commit is contained in:
Oleksii Trekhleb
2018-03-28 17:01:46 +03:00
parent 159d489e52
commit 8da6754523
9 changed files with 189 additions and 48 deletions

View File

@@ -0,0 +1 @@
# Queue

View 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;
}
}

View 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();
});
});