ygreenb
yellowgreenblue
ygreenb
전체 방문자
오늘
어제
  • TIL (130)
    • Algorithm & Data Structure (70)
      • 이론 (4)
      • 프로그래머스 (54)
      • 백준 (12)
    • JAVA (4)
    • Android Studio (9)
    • Database (1)
    • WEB (25)
      • HTML+CSS (7)
      • Javascript (5)
      • React (11)
      • Django (1)
      • Node.js (1)
    • Computer Vision (13)
    • Git (8)

블로그 메뉴

  • HOME
  • TAG
  • GITHUB

공지사항

인기 글

태그

  • BFS
  • 안드로이드
  • sort
  • Comparator
  • reactjs
  • 코틀린
  • git
  • React
  • HashMap
  • git bash
  • Arrays.sort()
  • getOrDefault
  • compareTo()
  • PriorityQueue
  • 스택/큐
  • greedy
  • Queue
  • 프로그래머스 Lv.2
  • DP
  • java
  • entrySet
  • 깃허브
  • 깃
  • 프로그래머스
  • 해시
  • kotiln
  • Android
  • dfs
  • 백준
  • stack

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
ygreenb

yellowgreenblue

[Java] 스택(Stack)과 큐(Queue) Java로 구현하기
JAVA

[Java] 스택(Stack)과 큐(Queue) Java로 구현하기

2022. 2. 27. 17:26

이번 포스팅에서는 스택과 큐를 자바에서 구현하는 방법에 대해 설명하려고 한다.
스택(Stack)과 큐(Queue)의 대한 기본적인 개념은 이전 포스팅에 정리 했었다.

 


자바에서 Stack 사용하기

자바에서 스택은 Stack 클래스를 구현하여 제공하고 있다.

Stack st = new Stack();

Stack의 메서드

메서드 설명
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 반환(배열과 달리 위치가 1부터 시작)

 

자바에서 Queue 사용하기

자바에서 큐는 인터페이스로만 정의해놓았을 뿐 별도의 클래스를 제공하고 있지 않다. 따라서 Queue 클래스 인스턴스를 생성하기 위해 Queue의 인터페이스 구현체인 LinkedList() 생성자를 호출해준다.

Queue q = new LinkedList();

Queue의 메서드

메서드 설명
boolean add(Object o) 지정된 객체를 Queue 에 추가
성공하면 true 반환, 저장공간이 부족하면 IllegalstateException 발생
Object element()
삭제없이 요소를 읽어옴
peek와 달리 Queue가 비었을 때 NoSuchElementException 발생
boolean offer(Object o) Queue 에 객체를 저장
성공하면 true, 실패하면 false 반환
Ojbect peek()
삭제없이 요소를 읽어옴
Queue 가 비어있으면 null을 반환
Object poll()
Queue 에서 객체를 꺼내서 반환.
비어있으면 null을 반환
Object remove() Queue 에서 객체를 꺼내 반환
비어잇으면 NoSuchElementException 발생

 

예제

import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
 
public class StackAndQueue {
    public static void main(String[] args) {
        Stack<String> stack = new Stack<String>();
        stack.push("0");
        stack.push("1");
        stack.push("2");
 
        Queue<String> queue = new LinkedList<String>();
        queue.offer("0");
        queue.offer("1");
        queue.offer("2");
        
        /*queue.add("3");
        queue.add("4");
        queue.add("5");*/
 
        System.out.println("=== Stack ===");
        while (!stack.empty()) {
            System.out.println(stack.pop());
        }
 
        System.out.println("=== Queue ===");
        while (!queue.isEmpty()) {
            System.out.println(queue.poll());
        }       
    }
}

실행결과


참고

 

Stack (Java Platform SE 8 )

The Stack class represents a last-in-first-out (LIFO) stack of objects. It extends class Vector with five operations that allow a vector to be treated as a stack. The usual push and pop operations are provided, as well as a method to peek at the top item o

docs.oracle.com

 

Queue (Java Platform SE 8 )

A collection designed for holding elements prior to processing. Besides basic Collection operations, queues provide additional insertion, extraction, and inspection operations. Each of these methods exists in two forms: one throws an exception if the opera

docs.oracle.com

 

저작자표시 (새창열림)

'JAVA' 카테고리의 다른 글

[Java] 문자열 비교 ==, equals() 차이점  (0) 2022.09.03
[Java] int와 Integer의 차이  (0) 2022.09.02
[JAVA] static(정적) 변수와 메소드  (1) 2022.01.13
    'JAVA' 카테고리의 다른 글
    • [Java] 문자열 비교 ==, equals() 차이점
    • [Java] int와 Integer의 차이
    • [JAVA] static(정적) 변수와 메소드
    ygreenb
    ygreenb
    개발공부기록장

    티스토리툴바