Skip to content

Instantly share code, notes, and snippets.

@ibogun
Created February 10, 2016 20:04
Show Gist options
  • Save ibogun/77e55e7519e0c6120c34 to your computer and use it in GitHub Desktop.
Save ibogun/77e55e7519e0c6120c34 to your computer and use it in GitHub Desktop.
Array implementation of the list
public class List {
private int[] list;
int size = 0;
int tail = 0;
final int INITIAL_SIZE = 8;
public List() {
list = new int[INITIAL_SIZE];
}
public List(int n) {
list = new int[n];
}
public boolean isFull() {
return (tail == list.length - 1);
}
public void insertEnd(int v) {
if (!isFull()) {
list[tail] = v;
tail++;
size++;
}
}
public void insertBeginning(int v) {
if(!isFull()) {
for (int i = tail - 1; i >= 0; i--) {
list[i+1] = list[i];
}
list[0] =v;
tail++;
size++;
}
}
public boolean isEmpty() {
return (tail==0);
}
public void delete(int v) {
if(!isEmpty()){
int i = 0;
while( v!= list[i] && i < tail) i++; // find index of
// the element to delete
if (i < tail) {
for (int j = i; j <=tail - 2; j++) { // move all elements
// one index to the left
list[j] = list[j+1];
}
size--;
tail--;
}
}
}
public String toString() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < size; i++) {
sb.append(list[i] +" ");
}
return new String(sb);
}
public static void main(String[] args) {
List l = new List();
System.out.println("--- Insert in the end ---");
l.insertEnd(12);
l.insertEnd(3);
l.insertEnd(33);
l.insertEnd(7);
l.insertEnd(2);
l.insertEnd(40);
System.out.println(l);
System.out.println("--- Insert in the beginning ---");
l.insertBeginning(22);
System.out.println(l);
System.out.println("--- Delete---");
l.delete(33);
System.out.println(l);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment