Preparing Coding Test/Algorithm
[자료구조/Java] Queue 구현하기 in Java
weero
2020. 9. 9. 13:05
www.youtube.com/watch?v=W3jNbNGyjMs
선입선출 방식(First-In First-Out, FIFO)
1) add()
2) remove()
3) peek()
4) isEmpty()
import java.util.NoSuchElementException;
class Queue<T>{
class Node<T>{
private T data;
private Node<T> next;
public Node(T data){
this.data = data;
}
}
private Node<T> first;
private Node<T> last;
public void add(T item){
Node<T> t = new Node<T>(item);
if(last != null){
last.next = t;
}
last = t;
//큐가 비어있을 때
if(first == null){
first = last;
}
}
public T remove(){
if(first == null)
throw new NoSuchElementException();
T data = first.data;
first = first.next;
if(first == null)
last = null;
return data;
}
public T peek(){
if(first == null)
throw new NoSuchElementException();
return first.data;
}
public boolean isEmpty(){
return first == null;
}
}
public class Main{
public static void main(String[] args){
Queue<Integer> queue = new Queue<Integer>();
q.add(1);
q.add(2);
q.add(3);
q.add(4);
System.out.println(q.remove());
System.out.println(q.remove());
System.out.println(q.peek());
System.out.println(q.remove());
System.out.println(q.isEmpty());
System.out.println(q.remove());
System.out.println(q.isEmpty());
}
}