개발공부/자료구조
자바 Queue(큐란?)
우주먼지쪼가리
2020. 12. 19. 15:40
반응형
package list.doublelinkedlist.implementation;
import java.util.NoSuchElementException;
public class Main {
public static void main(String[] args) {
Queue<Integer> p = new Queue<Integer>();
p.add(1);
p.add(2);
p.add(3);
p.add(4);
System.out.println(p.remove());
System.out.println(p.remove());
System.out.println(p.peek());
System.out.println(p.remove());
System.out.println(p.remove());
System.out.println(p.isEmpty());
}
}
class Queue<T>{
//같은 타입을 받는 노드
class Node<T>{
private T data;
private Node<T> next; //제너릭을 써서 개린이는 이해하기 어려웠지만, T가 없다고 생가하고 Node next; 라고 읽으면 이해가 쉬움.
//생성자에서 해당타입의 데이터를 받아서 내부변수(data)에 저장.
public Node(T data){
this.data = data;
}
}
private Node<T> first;
private Node<T> last;
//맨 뒤에 추가해주는거
public void add(T data){
Node<T> t = new Node<>(data);
if(last != null){
last.next = t;
}
last = t;
if(first == null){
first = last;
}
}
//맨 앞에서 데이터를 꺼내는거
public T remove(){
if(first == null){
throw new NoSuchElementException(); // 꺼낼 데이터 없음
}
//꺼내오기전에 꺼내올 다음 노드를 first로 만들어줘야 하니까
T data = first.data;
first = first.next;
if(first == null){ //first가 없으면 라스트도 없다.
last = null;
}
return data;
}
//맨 앞에 있는 데이터를 보는거
public T peek(){
if(first == null){
throw new NoSuchElementException();
}
return first.data;
}
// queue가 비었나 확인 하는거
public boolean isEmpty(){
return first == null;
}
}
반응형