Advertisement
Guest User

Untitled

a guest
Jun 24th, 2017
49
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.77 KB | None | 0 0
  1. public class DropOutStakSingleLinkedList<E> implements Stak<E> {
  2.     private Node head = null;
  3.     private int size = 0;
  4.     private int maxSize;
  5.  
  6.     public DropOutStakSingleLinkedList(int maxSize) {
  7.         if (maxSize < 0) maxSize = 1;
  8.         this.maxSize = maxSize;
  9.     }
  10.  
  11.     public void push(E object) {
  12.         Node node = new Node(object, head);
  13.  
  14.         if (size == maxSize) {
  15.             if (maxSize == 1) {
  16.                 node.next = head.next;
  17.             } else {
  18.                 Node cursor = head;
  19.                 while (cursor.next.next != null) {
  20.                     cursor = cursor.next;
  21.                 }
  22.                 cursor.next = null;
  23.             }
  24.             size--;
  25.         }
  26.  
  27.         head = node;
  28.         size++;
  29.     }
  30.  
  31.     public E pop() {
  32.         if (isEmpty()) throw new StakTomException("Stakken er tom");
  33.         Node temp = head;
  34.         head = head.next;
  35.         size--;
  36.         return temp.element;
  37.     }
  38.  
  39.     public E top() {
  40.         if (isEmpty()) throw new StakTomException("Stakken er tom");
  41.         return head.element;
  42.     }
  43.  
  44.     public int size() {
  45.         return size;
  46.     }
  47.  
  48.     public boolean isEmpty() {
  49.         return (head == null);
  50.     }
  51.  
  52.     public String toString() {
  53.         if (isEmpty()) return "[]";
  54.  
  55.         StringBuilder b = new StringBuilder(3 * size);
  56.         b.append('[');
  57.         Node cursor = head;
  58.         for (int i = 0;; i++) {
  59.             b.append(cursor.element);
  60.             if (i == size - 1) return b.append(']').toString();
  61.             b.append(", ");
  62.             cursor = cursor.next;
  63.         }
  64.     }
  65.  
  66.     private class Node {
  67.         E element;
  68.         Node next;
  69.  
  70.         Node(E element, Node next) {
  71.             this.element = element;
  72.             this.next = next;
  73.         }
  74.     }
  75.  
  76.     public static void main(String[] args) {
  77.         DropOutStakSingleLinkedList<Integer> ints = new DropOutStakSingleLinkedList<Integer>(3);
  78.  
  79.         ints.push(1); System.out.println(ints);
  80.         ints.push(2); System.out.println(ints);
  81.         ints.push(3); System.out.println(ints);
  82.         ints.push(4); System.out.println(ints);
  83.         ints.pop(); System.out.println(ints);
  84.     }
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement