-
[Data Structure] Java ํ(Queue) ์ฌ์ฉData Structure 2021. 1. 15. 14:15๋ฐ์ํ
- ์ด ๊ธ์ "์จ๋ผ์ธ ์๋ฐ ์คํฐ๋ ๋ด์ฉ"์ ์ ๋ฆฌํ ๊ธ์ ๋๋ค.
Queue๋?
- ํ๋ ์ถ๊ตฌ์ ์ ๊ตฌ๊ฐ ๋ช ๋ฐฑํ ์กด์ฌํ์ฌ ๋ฐ์ดํฐ๋ฅผ ๋ด๋ ๋ฐฉ์์ ์๋ฃ๊ตฌ์กฐ์ ๋๋ค.
- ํ์ ์ฃผ์ ํน์ง์ First In, First Out (FIFO) ๊ตฌ์กฐ๋ฅผ ๊ฐ์ต๋๋ค.
๋ฐฐ์ด๋ก ํ ๊ตฌํ
public class Queue {
public class Queue { final int MAX_SIZE = 100; int[] arr; int size; public Queue() { arr = new int[MAX_SIZE]; size = 0; } void push(int data){ arr[size++] = data; } int front(){ return arr[0]; } int pop(){ if(size == 0){ return 0; } else{ for(int i=1;i<size;i++){ arr[i-1] = arr[i]; } size--; return 1; } } public int getSize() { return size; } }
public class Main { public static void main(String[] args) { Queue queue = new Queue(); queue.push(1); queue.push(2); queue.push(3); System.out.println(queue.getSize()); // 3 System.out.println(queue.front()); // 1 queue.pop(); System.out.println(queue.front()); // 2 queue.pop(); System.out.println(queue.front()); // 3 queue.pop(); } }
๋ ธ๋๋ก ํ ๊ตฌํ
public class ListNode { int data; ListNode next; public ListNode(int data) { this.data = data; next = null; } }
๋ค์ ํด๋์ค๋ ๋ ธ๋๋ฅผ ๊ตฌํํ๋ ์ฝ๋์ ๋๋ค.
public class ListNodeQueue { ListNode head; int size; public ListNodeQueue() { head = null; size = 0; } void push(int data){ ListNode node = head; if(size == 0){ node = new ListNode(data); head = node; }else{ while (node.next!=null){ node = node.next; } node.next = new ListNode(data); } size++; } int pop(){ if(size == 0){ return 0; } else { head = head.next; size--; return 1; } } int front(){ return head.data; } public int getSize() { return size; } }
public class Main { public static void main(String[] args) { ListNodeQueue queue = new ListNodeQueue(); queue.push(1); queue.push(2); queue.push(3); System.out.println(queue.front()); // 1 queue.pop(); System.out.println(queue.front()); // 2 queue.pop(); System.out.println(queue.front()); // 3 queue.pop(); } }
๋ฐ์ํ'Data Structure' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Data Structure] Deque ์ฌ์ฉ๋ฒ (0) 2021.08.01 [Data Structure] Java ์ด์งํธ๋ฆฌ(Binary Tree) ๊ตฌํ (0) 2021.01.17 [Data Structure] Java ์คํ(Stack) ์ฌ์ฉ (0) 2021.01.15 [Data Structure] Java ๋งํฌ๋ ๋ฆฌ์คํธ(LinkedList) ๊ตฌํ (0) 2021.01.15 [Data Structure] multimap ์ฌ์ฉ๋ฒ (0) 2020.11.08