SevdanurGenc's picture
Upload 60 files
63f6453 verified
Raw History Blame Contribute Delete
1.77 kB
import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;
/** Kapasitesi sınırlı yığın (stack). */
public class BoundedStack<T> {
private final List<T> items = new ArrayList<>();
private final int capacity;
public BoundedStack(int capacity) {
if (capacity <= 0) {
throw new IllegalArgumentException("capacity must be positive");
}
this.capacity = capacity;
}
public void push(T item) {
if (item == null) {
throw new NullPointerException("null items are not allowed");
}
if (isFull()) {
throw new IllegalStateException("stack is full");
}
items.add(item);
}
public T pop() {
if (isEmpty()) {
throw new NoSuchElementException("stack is empty");
}
return items.remove(items.size() - 1);
}
public T peek() {
if (isEmpty()) {
throw new NoSuchElementException("stack is empty");
}
return items.get(items.size() - 1);
}
/** Yığının en üstündeki n elemanı (üstten alta) döndürür; n büyükse tümü. */
public List<T> top(int n) {
if (n < 0) {
throw new IllegalArgumentException("n must be >= 0");
}
List<T> out = new ArrayList<>();
for (int i = items.size() - 1; i >= 0 && out.size() < n; i--) {
out.add(items.get(i));
}
return out;
}
public int size() {
return items.size();
}
public boolean isEmpty() {
return items.isEmpty();
}
public boolean isFull() {
return items.size() == capacity;
}
public int remaining() {
return capacity - items.size();
}
}