File size: 1,767 Bytes
63f6453
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
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();
    }
}