포스트

QUEUE 자료구조 구현

FIFO : First In First Out

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import java.util.NoSuchElementException;  
  
/**  
  
 - Stack 자료구조 구현  
 - FILO : first in last out  
*/  
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 data) {  
        Node<T> tmp = new Node<T>(data);  
  
        // 첫번째 포인터 노드가 널인 경우  
        if (first == null) {  
            first = tmp;  
            // 마지막 노드 = 첫번째 노드  
            last = first;  
        }else {  
            // 마지막 노드의 다음 포인터에 저장  
            last.next = tmp;  
  
            // 노드 이동  
            last = last.next;  
        }  
    }  
  
    public T remove() {  
        if(first == null) {  
            throw new NoSuchElementException();  
        }  
  
        T tmp = first.data;  
  
        first = first.next;  
  
        if (first == null) {  
            last = null;  
        }  
  
        return tmp;  
    }  
  
    public T peek() {  
        if (first == null) {  
            throw new NoSuchElementException();  
        }  
        return first.data;  
    }  
  
    public boolean isEmpty(){  
        return first == null;  
    }  
}  
  
  
public class test {  
    public static void main (String[] args) {  
        System.out.println("hello world");  
  
        Queue<Integer> queue = new Queue<>();  
  
        queue.add(1);  
        queue.add(2);  
        queue.add(3);  
  
        queue.remove();  
        queue.remove();  
        queue.remove();  
  
        System.out.println("Exit");  
    }  
}
이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.