반응형
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;
}
}
반응형
'개발공부 > 자료구조' 카테고리의 다른 글
네트워크란? (0) | 2020.12.19 |
---|---|
제네릭이란?(자바 <> 이게 뭔가요?) (0) | 2020.12.15 |
인터페이스란? (0) | 2020.12.15 |
Collections framework(list, set, map) (0) | 2020.12.11 |
Doubly linked list(양방향 연결 리스트) (0) | 2020.12.09 |