Last active
July 15, 2017 02:24
-
-
Save pathikrit/8616b2869dc441f02084 to your computer and use it in GitHub Desktop.
Data structure that supports O(1) append, prepend, first, last and size
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.ArrayList; | |
public class FastPrependArrayList<A> { | |
private ArrayList<A> appends = new ArrayList<A>(); | |
private ArrayList<A> prepends = new ArrayList<A>(); | |
public void append(A element) { | |
appends.add(element); | |
} | |
public void prepend(A element) { | |
prepends.add(element); | |
} | |
public A get(int index) { | |
return index < prepends.size() ? prepends.get(prepends.size() - index - 1) : appends.get(index + prepends.size()); | |
} | |
public int size() { | |
return prepends.size() + appends.size(); | |
} | |
public A first() { | |
return get(0); | |
} | |
public A last() { | |
return get(size() - 1); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
line 16: should be
-
@: appends.get(index + prepends.size());
instead of+
👍