사진과코딩

[Java] Stack, Queue 본문

Java

[Java] Stack, Queue

Dev_Fuji 2024. 6. 11. 22:34

Stack

  • LIFO 자료 구조
  • Stack<T> stack = new Stack<>()으로 선언한다.
  • DFS 구현 시 사용
리턴타입 메소드 설명
 T push(T t1) 매개변수를 스택에 넣는다
T pop() 스택 맨 위 객체를 뺀다.

 

Queue

  • FIFO 자료 구조
  • Queye<T> queue = new LinkedList<T>()로 선언
  • BFS 구현 시 사용
리턴타입 메소드 설명
boolean offer(T t1) 큐에 객체를 넣는다
T poll() 큐에서 객체를 뺀다

 

Priority Queue

  • 우선순위 큐로 들어온 순서와 상과없이 우선순위가 높은 데이터가 먼저 나간다.
  • 힙을 이용하여 구현한다.
public static void main(String[] args) {
    PriorityQueue<Integer> priorityQueue = new PriorityQueue<>(); //작은 숫자 먼저 출력
    PriorityQueue<Integer> priorityQueue1 = new PriorityQueue<>(Collections.reverseOrder()); //큰 숫자 먼저 출력
}
메소드 설명
add() 큐에 원소 추가, 꼭 찬 경우 에러발생
offer() 큐에 원소 추가, 추가 실패 시 false 발생
remove() 첫 번째 값 반환 후 실행 종료
isEmpty() 큐가 비어있는지 확인
clear() 큐를 비운다
size() 큐의 원소의 수를 반환

 

import java.util.*;
public class Main {
    public static void main(String[] args) {
        Person p1 = new Person(20,"kim");
        Person p2 = new Person(10,"jong");
        Person p3 = new Person(30,"hong");
        Comparator<Person> comp = new Comparator<Person>(){
            @Override
            public int compare(Person p1, Person p2){
                return p1.age-p2.age;
            }
        };
        Comparator<Person> comp2 = new Comparator<Person>(){
            @Override
            public int compare(Person p1, Person p2){
                return p2.age - p1.age;
            }
        };
        PriorityQueue<Person> priorityQueue = new PriorityQueue<>(comp);
        priorityQueue.add(p1);
        priorityQueue.add(p2);
        priorityQueue.add(p3);
        PriorityQueue<Person> priorityQueue1 = new PriorityQueue<>(comp2);
        priorityQueue1.add(p1);
        priorityQueue1.add(p2);
        priorityQueue1.add(p3);
        while(!priorityQueue.isEmpty()) System.out.println("priorityQueue = "+priorityQueue.remove().age);
        while(!priorityQueue1.isEmpty()) System.out.println("priorityQueue1 = "+priorityQueue1.remove().age);
    }

    public static class Person {
        int age;
        String name;
        public Person(int age, String name) {
            this.age = age;
            this.name = name;
        }
    }
}

> Task :Main.main()
priorityQueue = 10
priorityQueue = 20
priorityQueue = 30
priorityQueue1 = 30
priorityQueue1 = 20
priorityQueue1 = 10

'Java' 카테고리의 다른 글

[Java] Stream  (0) 2024.06.12
[Java] Comparable, Comparator  (0) 2024.06.11
[Java] 컬렉션  (1) 2024.06.11
[Java] 인터페이스  (0) 2024.06.11
[Java] 상속  (0) 2024.06.10