Stack(스택)
한 쪽 끝에서만 자료를 넣거나 뺄 수 있는 선형 및 Last in First Out(LIFO) 구조의 자료구조.
Java에서 자료구조(알고리즘)를 만들 때, 해당 객체에 대한 설계도(ADT, Abstract Data Type)를 Interface로 구현한다.
코드
(1) Stackable.java : Stack이라면 갖춰야 할 ADT(객체에 대한 설계도)를 Interface로 구현. (Java에서 Interface를 ADT로 사용함)
(2) ArrayListStack.java : ArrayList를 이용한 Stack 구현.
(1) Stackable.java
/* Stackable.java */
public interface Stackable<E> {
// access: isEmpty
// if my elements exist, or not: false, true
public boolean isEmpty();
// access: push
// insert a elements to last of Stack
public void push(E element);
// access: pop
// get a elements from first of Stack with deletion
public E pop();
// access top
// get a elements from first of Stack without deletion
public E top();
}
(2) ArrayListStack.java
/* ArrayListStack.java */
public class ArrayListStack<E> implements Stackable<E> {
List<E> list;
public ArrayListStack() {
this.list = new ArrayList<>();
}
public boolean isEmpty() {
return this.list.isEmpty();
}
public void push(E element) {
this.list.add(element);
}
public E pop() {
E result = this.list.get(this.list.size() - 1);
this.list.remove(this.list.size() - 1);
return result;
}
public E top() {
E result = this.list.get(this.list.size() - 1);
return result;
}
}
class Test2 {
public static void main(String[] args) {
ArrayListStack<String> listStack = new ArrayListStack<>();
listStack.push("!!!");
listStack.push("World");
listStack.push("Hello");
System.out.println(listStack.top());
System.out.println(listStack.pop());
System.out.println(listStack.pop());
System.out.println(listStack.pop());
}
}
실행 결과
Hello
Hello
World
!!!
2024.09.02 - [자료구조] - [Java] ArrayList
[Java] ArrayList
ArrayList배열을 기반으로 한 컬렉션의 하나다.List Interface를 상속받은 클래스 중 하나이다.read가 빠르지만, insert/delete가 느리다. (삽입, 삭제가 적고, 작은 데이터를 다룰 때 사용) 코드(1) List.java :
lightningtech.tistory.com
출처: https://github.com/gikpreet/class-programming_with_java/tree/master
GitHub - gikpreet/class-programming_with_java
Contribute to gikpreet/class-programming_with_java development by creating an account on GitHub.
github.com
'자료구조' 카테고리의 다른 글
[자료구조] LinkedList (0) | 2024.09.04 |
---|---|
[Java] ArrayList (0) | 2024.09.02 |
[자료구조] 삽입 정렬 (Insertion Sort) (0) | 2024.08.27 |
[자료구조] 선택 정렬 (Selection Sort) (0) | 2024.08.27 |
[자료구조] 버블 정렬 (Bubble Sort) (0) | 2024.08.22 |