티스토리 뷰

1. Stack

 - LIFO (Last In First Out) 를 구현한 자료구조 (처음 삽입한 객체는 가장 마지막에, 가장 최근에 삽입한 객체는 가장 처음으로 꺼내는 방식)

 - 함수 내의 변수들이 임시로 저장되는 공간





2. Queue

 - FIFO (First In First Out) 를 구현한 자료구조 (처음 삽입한 객체를 먼저 꺼내는 방식)

 - 아래는 큐의 구현클래스인 우선순위큐(Priority Queue)를 활용한 예제이다.

   우선순위큐는 정렬기준의 맞추어 순차적으로 출력이 되는 큐를 의미

   아래에서 정렬의 우선순위를 학생의 학년으로 설정하였고, 우선순위에 맞게 출력이 될 수 있도록 설정했다.

   그리고 Student 클래스에서 grade 로 정렬을 하기 위해 Comparable 인터페이스를 구현하여 CompareTo 메소드를 오버라이딩 했다.


   



 (1) Student 클래스 ( 정렬기준을 compareTo()로 구현 - grade 기준)

package queue;

public class Student implements Comparable{
	private String name;
	private int grade;
	
	public Student(String name, int grade) {
		//super();
		this.name = name;
		this.grade = grade;
	}

	@Override
	public int compareTo(Student other) {
		if(this.grade > other.grade) return 1;
		else if (this.grade < other.grade) return -1;
		else return 0;
	}

	@Override
	public String toString() {
		return "Student [name=" + name + ", grade=" + grade + "]";
	}
	
}


 (2) Main 클래스 (Priority Queue 구현 후, grade 기준 오름차순, 내림차순으로 출력)
  - Queue는 Collection 이기 때문에 Collections.reverOrder() 를 이용해서 내림차순으로 구현 가능

package queue;

import java.util.Collections;
import java.util.PriorityQueue;
import java.util.Queue;

public class QueueExample {

	public static void main(String[] args) {
		/* 오름차순 정렬 */
		Queue priorityQueue = new PriorityQueue();
		priorityQueue.offer(new Student("LEE", 2)); 
		priorityQueue.offer(new Student("CHOI", 3)); 
		priorityQueue.offer(new Student("PARK", 1));
		
		while(!priorityQueue.isEmpty()) {
			System.out.println(priorityQueue.poll().toString());
		}
		
		/* 내림차순 정렬 */
		Queue priorityReverseQueue = new PriorityQueue(Collections.reverseOrder());
		priorityReverseQueue.offer(new Student("LEE", 2)); 
		priorityReverseQueue.offer(new Student("CHOI", 3)); 
		priorityReverseQueue.offer(new Student("PARK", 1));
		
		while(!priorityReverseQueue.isEmpty()) {
			System.out.println(priorityReverseQueue.poll().toString());
		}
	}

}


3.Deque

 - 덱 양 끝에서 삽입과 삭제가 모두 가능한, 스택과 큐의 성격을 모두 갖는 자료구조



공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함