Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class DropOutStakSingleLinkedList<E> implements Stak<E> {
- private Node head = null;
- private int size = 0;
- private int maxSize;
- public DropOutStakSingleLinkedList(int maxSize) {
- if (maxSize < 0) maxSize = 1;
- this.maxSize = maxSize;
- }
- public void push(E object) {
- Node node = new Node(object, head);
- if (size == maxSize) {
- if (maxSize == 1) {
- node.next = head.next;
- } else {
- Node cursor = head;
- while (cursor.next.next != null) {
- cursor = cursor.next;
- }
- cursor.next = null;
- }
- size--;
- }
- head = node;
- size++;
- }
- public E pop() {
- if (isEmpty()) throw new StakTomException("Stakken er tom");
- Node temp = head;
- head = head.next;
- size--;
- return temp.element;
- }
- public E top() {
- if (isEmpty()) throw new StakTomException("Stakken er tom");
- return head.element;
- }
- public int size() {
- return size;
- }
- public boolean isEmpty() {
- return (head == null);
- }
- public String toString() {
- if (isEmpty()) return "[]";
- StringBuilder b = new StringBuilder(3 * size);
- b.append('[');
- Node cursor = head;
- for (int i = 0;; i++) {
- b.append(cursor.element);
- if (i == size - 1) return b.append(']').toString();
- b.append(", ");
- cursor = cursor.next;
- }
- }
- private class Node {
- E element;
- Node next;
- Node(E element, Node next) {
- this.element = element;
- this.next = next;
- }
- }
- public static void main(String[] args) {
- DropOutStakSingleLinkedList<Integer> ints = new DropOutStakSingleLinkedList<Integer>(3);
- ints.push(1); System.out.println(ints);
- ints.push(2); System.out.println(ints);
- ints.push(3); System.out.println(ints);
- ints.push(4); System.out.println(ints);
- ints.pop(); System.out.println(ints);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement