[Data Structure] JavaScript Stack 구현
Stack 구현
1function Stack(){
2 let items = [];
3
4 this.push = function(element) {
5 items.push(element);
6 };
7
8 this.pop = function() {
9 return items.pop();
10 };
11
12 this.peek = function() {
13 return items[items.length-1];
14 };
15
16 this.isEmpty = function(){
17 return items.length === 0;
18 };
19
20 this.size = function(){
21 return items.length;
22 };
23
24 this.clear = function(){
25 items = [];
26 };
27
28 this.print = function(){
29 console.log(items.toString());
30 };
31};
32
33let stack = new Stack();
34console.log(stack.isEmpty());
35
36
37// Test
38stack.push(1);
39stack.push(2);
40stack.push(3);
41stack.print();
42console.log(stack.size());
43console.log(stack.isEmpty());
44
45stack.pop();
46stack.pop();
47stack.print();
예제 : 10진수 -> 2진수 변환
10진수를 2진수로 바꾸는 방법 : 몫이 0이 될 때까지 2로 나눈다.
1function diviedeBy2(decNumber) {
2 let remStack = new Stack();
3 let rem;
4 let binaryString = '';
5
6 while (decNumber > 0){
7 rem = Math.floor(decNumber % 2);
8 remStack.push(rem);
9 decNumber = Math.floor(decNumber / 2);
10 }
11
12 while (!remStack.isEmpty()){
13 binaryString += remStack.pop().toString();
14 }
15
16 return binaryString;
17}
18
19console.log(diviedeBy2(240)); // 11110000