스택 / 큐

류장원·2024년 8월 17일

📌 스택(Stack)이란 무엇일까?

  • 상자에 물건을 쌓아 올리듯이 데이터를 쌓는 자료 구조
  • LIFO(Last In First Out) : 마지막에 저장한 데이터를 가장 먼저 꺼내게 되는 구조 특징

[출처] : https://inpa.tistory.com/entry/JCF-🧱-Stack-구조-사용법-정리

  • 스택 사용 사례
    • 웹 브라우저 방문 기록(뒤로 가기)
    • 실행 취소(Undo)
    • 역순 문자열 만들기
    • 후위 표기법 계산

📌 Stack 사용법 in JAVA

메서드설명
boolean empty()Stack이 비어있는지 알려준다
Object peek()Stack의 맨 위에 저장된 객체를 반환. pop과 달리 Stack에서 객체를 꺼내지는 않는다.  비어있을 경우 EmptyStackException 발생
Object pop()Stack의 맨 위에 저장된 객체를 꺼낸다. 비어있을 경우 EmptyStackException 발생
Object push(Object item)Stack에 객체(item)를 저장한다
int search(Object o)Stack에서 주어진 객체(o)를 찾아서 그 위치를 반환 

못 찾을 경우 -1을 반환 
배열과 달리 위치는 0이 아닌 1부터 시작 |


📌 Stack 대신 Deque 사용

  • 결론부터 보면, 자바의 스택 클래스는 쓰기를 지양하여야 한다.
  • 스택은 Vector 컬렉션을 상속받는 데 이 컬렉션이 오래되어서 문제점이 많이 발생한다.
  • 따라 Stack 클래스보단 Deque 클래스 사용을 권장한다.
/* Stack 처럼 사용하기 */
Deque<String> stack = new ArrayDeque<>();

stack.push("a");
stack.push("b");
stack.push("c");
stack.push("d");
stack.push("e");

System.out.println(stack); // [a, b, c, d, e]

System.out.println(stack.pop()); // e
System.out.println(stack.pop()); // d

System.out.println(stack); // [a, b, c]

📌 큐(Queue)란 무엇일까?

  • FIFO(First In First Out) : 스택과 달리 먼저 들어온 것이 먼저 나가는 선입선출
  • Front(프론트) : 삭제 연산이 수행되는 곳 / Rear(리어) : 삽입 연산이 수행되는 곳
  • Enqueue : 삽입 연산 / Dequeue : 삭제 연산

📌 Queue 사용법 in JAVA

  • Queue 선언
import java.util.LinkedList;
import java.util.Queue;
Queue<Integer> q = new LinkedList<>(); // int형 queue 선언
Queue<String> q = new LinkedList<>(); // String형 queue 선언
  • Queue 값 추가(offer())
Queue<Integer> q = new LinkedList<>(); // int형 queue 선언

q.offer(3);
q.offer(5);
q.offer(1);
q.offer(4);

System.out.println(q); // 출력 결과 : [3, 5, 1, 4]

→ add()를 사용해서 값 추가할 수 있다. 차이점은 add()는 예외 발생, offer()은 false 리턴

  • Queue 값 삭제(poll())
Queue<Integer> q = new LinkedList<>(); // int형 queue 선언

q.offer(3);
q.offer(5);
q.offer(1);
q.offer(4);

q.poll();
System.out.println(q); // 출력 결과 : [5, 1, 4]
q.clear();
System.out.println(q); // 출력 결과 : []
  • Queue에서 가장 먼저 들어간 값
Queue<Integer> q = new LinkedList<>(); // int형 queue 선언

q.offer(3);
q.offer(5);
q.offer(1);
q.offer(4);

System.out.println(q.peek()); // 출력 결과 : 3
profile
Mythos of Summer

0개의 댓글