Skip to content

Commit f9a9f5e

Browse files
committed
feat : stack, queue 구현
``` Stack.java Queue 두개를 이용해 Stack 구현 Queue.java Stack 두개를 이용해 Queue 구현 ```
1 parent efcc9c2 commit f9a9f5e

File tree

2 files changed

+71
-0
lines changed

2 files changed

+71
-0
lines changed

example/data_structure/Queue.java

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import java.io.BufferedReader;
2+
import java.io.IOException;
3+
import java.io.InputStreamReader;
4+
import java.util.Arrays;
5+
import java.util.Stack;
6+
7+
class Queue<T>{
8+
Stack<T> inStack;
9+
Stack<T> outStack;
10+
11+
public Queue () {
12+
this.inStack = new Stack<>();
13+
this.outStack = new Stack<>();
14+
}
15+
16+
public void offer(T obj){
17+
this.outStack.push( obj );
18+
}
19+
20+
public T poll(){
21+
while(!outStack.isEmpty()) {
22+
inStack.push(outStack.pop());
23+
}
24+
T number = inStack.pop();
25+
while(!inStack.isEmpty()) {
26+
outStack.push( inStack.pop() );
27+
}
28+
return number;
29+
}
30+
31+
public boolean isEmpty(){
32+
return outStack.isEmpty();
33+
}
34+
}

example/data_structure/Stack.java

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
import java.util.LinkedList;
2+
import java.util.Queue;
3+
4+
public class Stack<T> {
5+
6+
Queue<T> inQueue;
7+
Queue<T> outQueue;
8+
9+
public Stack(){
10+
this.inQueue = new LinkedList<>();
11+
this.outQueue = new LinkedList<>();
12+
}
13+
14+
public void push(T obj){
15+
this.outQueue.offer( obj );
16+
}
17+
18+
public T pop(){
19+
while ( outQueue.size() != 1){
20+
inQueue.offer( outQueue.poll() );
21+
}
22+
T poll = outQueue.poll();
23+
while ( !inQueue.isEmpty() ){
24+
outQueue.offer( inQueue.poll() );
25+
}
26+
return poll;
27+
}
28+
29+
public boolean isEmpty(){
30+
return outQueue.isEmpty();
31+
}
32+
33+
public int size(){
34+
return outQueue.size();
35+
}
36+
37+
}

0 commit comments

Comments
 (0)