Data Structure

[Data Structure] Java ํ(Queue) ์‚ฌ์šฉ

An effort will never betray ๐Ÿ˜Ž 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();
    }
}
๋ฐ˜์‘ํ˜•