JAVA
자바 알고리즘 정복 3 - 스택, 큐
세댕댕이
2021. 8. 7. 16:42
# 제네릭 스택(연결리스트 활용)
package StudyJava.Stack;
import java.util.EmptyStackException;
public class GenericStack<T> {
class Node<T> {
private T data;
private Node<T> next;
public Node(T data) {
this.data = data;
}
}
private Node<T> top;
public T pop() {
if(top == null) {
throw new EmptyStackException();
}
T item = top.data;
top = top.next;
return item;
}
public void push(T item) {
Node<T> t = new Node<T>(item);
t.next = top;
top = t;
}
public T peek() {
if(top == null) {
throw new EmptyStackException();
}
return top.data;
}
public boolean isEmpty() {
return top == null;
}
}
# 제네릭 큐(연결리스트 활용)
class Queue<T> {
class Node<T> {
private T data;
private Node<T> next;
public Node(T data) {
this.data = data;
}
}
private Node<T> first;
private Node<T> last;
public void add(T item) {
Node<T> t = new Node<T>(item);
if(last != null) {
last.next = t;
}
last = t;
if(first == null) {
first = last;
}
}
public T remove() {
if(first == null) {
throw new NoSuchElementException();
}
T data = first.data;
first = first.next;
if(first == null) { // 큐가 비었을때
last = null;
}
return data;
}
public T peek() {
if(first == null) {
throw new NoSuchElementException();
}
return first.data;
}
public boolean isEmpty() {
return first == null;
}
}