Skip to content

Instantly share code, notes, and snippets.

@Sisekelo
Created June 1, 2018 06:02
Show Gist options
  • Select an option

  • Save Sisekelo/6f91cdf76503c5b668bef8595dc28787 to your computer and use it in GitHub Desktop.

Select an option

Save Sisekelo/6f91cdf76503c5b668bef8595dc28787 to your computer and use it in GitHub Desktop.
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package stack;
import java.util.Arrays;
/**
*
* @author DELL
* @param <T>
*/
public class Stack<T> implements stackInterface<T> {
private T[] array;
//WHAT DOES THIS DO, WHAT ARE GENERICS
public Stack() {
this.array = new T[0];
}
/**
* @param t
*/
//we should use an array
@Override
public void push(T t) {
//creates a temp array with 1+ length from the first
T[] temp = new T[array.length+1];
//loops through array to add the old values
System.arraycopy(array, 0, temp, 0, array.length);
array = temp;
array[array.length-1] = t;
}
@Override
public T pop(T t) {
//if the array is empty return null
if(array.length == 0){
return null;
}
//value to be popped
T poppedValue;
poppedValue = array[array.length-1];
//make it smaller by one
T[] temp = new T[array.length-1];
//add from index 0 to 1 less
System.arraycopy(array, 0, temp, 0, array.length-1);
//return that first value
return poppedValue;
}
@Override
public T peek(T t) {
//this is just to see what value is at the top of the stack
//if the array is empty return null
if(array.length == 0){
return null;
}
return array[array.length-1];
}
@Override
public boolean empty() {
//checks if the array is empty
return array.length == 0;
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package stack;
/**
*
* @author DELL
* @param <T>
*/
public interface stackInterface <T> {
//adds object to top of the stack, doesnt return anything
void push(T t);
//removes object from top of the stack, returns the removed value
T pop(T t);
//checks what object is on top of stack
T peek(T t);
//checks if stack is empty, returns boolean
boolean empty();
}
@Omeiza17
Copy link

Omeiza17 commented Jun 1, 2018

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment