Advertisement
Guest User

Untitled

a guest
Aug 24th, 2019
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.06 KB | None | 0 0
  1. import java.util.Arrays;
  2.  
  3. public class StackImpl {
  4.  
  5.     private int[] array = new int[10];
  6.     int size = 0;
  7.  
  8.     public static void main(String[] args) {
  9.  
  10.     }
  11.  
  12.     public int size() {
  13.         return size;
  14.     }
  15.  
  16.     public boolean isEmpty() {
  17.         return size == 0;
  18.     }
  19.  
  20.     public void push(int element) {
  21.         if(size == array.lenth) {
  22.             // skapa ny lista med lenth*2 och lägga över alla element i samma ordning + det nya i slutet
  23.             array = Arrays.copyOf(array, array.lenth*2); // tror det fungerar
  24.         }
  25.         else {
  26.             //lägg till det nya elementet på plats size
  27.             array[size] = element;
  28.         }
  29.         size++;
  30.  
  31.     }
  32.  
  33.     public int pop() {
  34.         if(size <= 0) {
  35.             throw new IndexOutOfBoundsException();
  36.         } else {
  37.             size--;
  38.             return array[size];
  39.         }
  40.     }
  41.  
  42.     public int peek() {
  43.         if(size <= 0) {
  44.             throw new IndexOutOfBoundsException();
  45.         } else {
  46.             return array[size-1];
  47.         }
  48.     }
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement