Skip to content

Commit b630fe4

Browse files
committed
adding qforms
1 parent 95e3b85 commit b630fe4

File tree

3 files changed

+93
-0
lines changed

3 files changed

+93
-0
lines changed

qforms/directions.md

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
# --- Directions
2+
3+
Implement a Queue datastructure using two stacks.
4+
*Do not* create an array inside of the 'Queue' class.
5+
Queue should implement the methods 'add', 'remove', and 'peek'.
6+
For a reminder on what each method does, look back
7+
at the Queue exercise.
8+
9+
# --- Examples
10+
const q = new Queue();
11+
q.add(1);
12+
q.add(2);
13+
q.peek(); should returns 1
14+
q.remove(); should returns 1
15+
q.remove(); should returns 2
16+
17+
18+
# --- Solutions
19+

qforms/qforms.js

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
// --- Directions
2+
// Implement a Queue datastructure using two stacks.
3+
// *Do not* create an array inside of the 'Queue' class.
4+
// Queue should implement the methods 'add', 'remove', and 'peek'.
5+
// For a reminder on what each method does, look back
6+
// at the Queue exercise.
7+
8+
// --- Examples
9+
// const q = new Queue();
10+
// q.add(1);
11+
// q.add(2);
12+
// q.peek(); should returns 1
13+
// q.remove(); should returns 1
14+
// q.remove(); should returns 2
15+
16+
17+
// Solution
18+
19+
const Stack = require('./stack');
20+
21+
class Queue {
22+
constructor() {
23+
this.first = new Stack();
24+
this.second = new Stack();
25+
}
26+
27+
add(record) {
28+
this.first.push(record);
29+
}
30+
31+
remove() {
32+
while(this.first.peek()) {
33+
this.second.push(this.first.pop());
34+
}
35+
36+
const record = this.second.pop();
37+
38+
while(this.second.peek()) {
39+
this.first.push(this.second.pop());
40+
}
41+
42+
return record;
43+
}
44+
45+
46+
peek() {
47+
while(this.first.peek()) {
48+
this.second.push(this.first.pop());
49+
}
50+
51+
const record = this.second.peek();
52+
53+
while(this.second.peek()) {
54+
this.first.push(this.second.pop());
55+
}
56+
}
57+
}

qforms/stack.js

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
class Stack {
2+
constructor(){
3+
this.data = [];
4+
}
5+
6+
add(record) {
7+
this.data.push(record);
8+
}
9+
10+
remove() {
11+
return this.data.pop();
12+
}
13+
14+
peek(){
15+
return this.data[this.data.length -1];
16+
}
17+
}

0 commit comments

Comments
 (0)