카테고리 없음
[알고리즘] 큐(Queue)란 ?
상용최
2020. 2. 4. 16:17
반응형
큐(Queue)란 ?
- 제일 먼저 입력된것이 제일먼저 나오는 자료구조 (FIFO)
큐(Queue)의 연산
- 추가 : 큐의 제일 끝에 데이터를 추가한다. (구현부에서는 push로 구현)
- 삭제 : 큐의 제일 처음에 있는 데이터를 삭제한다. (구현부에서는 pop으로 구현)
- peek() : 큐의 제일 처음에 있는 데이터를 반환한다. (구현부에서는 front로 구현)
- isEmpty() : 비어있는지 검사한다. (구현부에서는 empty로 구현)
큐(Queue)의 구현
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Queue queue = new Queue();
Scanner sc = new Scanner(System.in);
int commandCnt =0;
String command = "";
commandCnt = sc.nextInt();
sc.nextLine();
for(int i=0; i<commandCnt; i++){
command = sc.nextLine();
if(command.contains("push")){
int value = Integer.parseInt(command.split(" ")[1]);
queue.push(value);
}else if(command.contains("pop")) {
queue.pop();
}else if(command.contains("front")) {
queue.front();
}else if(command.contains("back")) {
queue.back();
}else if(command.contains("empty")) {
queue.empty();
}else if(command.contains("size")) {
queue.size();
}
}
}
}
class Queue{
List<Integer> queue = new ArrayList<>();
public void push(int value){
queue.add(value);
}
public void pop(){
if(queue.size()>0){
System.out.println(queue.get(0));
queue.remove(0);
}else{
System.out.println("-1");
}
}
public void size(){
System.out.println(queue.size());
}
public void empty(){
if(queue.size()>0){
System.out.println("0");
}else {
System.out.println("1");
}
}
public void front(){
if(queue.size()>0){
System.out.println(queue.get(0));
}else{
System.out.println("-1");
}
}
public void back(){
if(queue.size()>0){
System.out.println(queue.get(queue.size()-1));
}else{
System.out.println("-1");
}
}
}
큐의 사용
- 캐시구현
- 우선순위
- 은행창구와 같이 FIFO이 필요한 작업
반응형