[이코테 by Java] Queue, Stack

YJ·2024년 10월 27일

🖍️ Queue

  • BFS 문제에 사용되는 자료구조.
import java.util.*;

public class DataStructureQueue {
    public static void main(String[] args) {
        Queue<Integer> q = new LinkedList<>();

        q.offer(5);
        q.offer(2);
        q.offer(3);
        q.offer(7);
        q.poll(); // 삭제
        q.offer(1);
        q.offer(4);
        q.poll();

        while (!q.isEmpty()) {
            System.out.println(q.poll());
        }
        
        // 출력 결과물
        // 3, 7, 1, 4
    }
}

🖍️ Stack

  • DFS 문제에 사용되는 자료구조.
import java.util.*;

public class DataStructureStack {
    public static void main(String[] args) {
        Stack<Integer> s = new Stack<>();

        s.push(5);
        s.push(2);
        s.push(3);
        s.push(7);
        s.pop();
        s.push(1);
        s.push(4);
        s.pop();

        while (!s.isEmpty()) {
            System.out.println(s.peek());
            s.pop();
        }

        // 출력 결과물
        // 1, 3, 2, 5
    }
}
profile
기록 안해놓잖아? 그럼 나중에 싹 다 잊어버리는 거예요 명심하기로 해요^.^

0개의 댓글