Skip to content

Instantly share code, notes, and snippets.

@schmohlio
Created January 14, 2019 00:44
Show Gist options
  • Save schmohlio/c0df1859ad18b65cedb51fac3258bafe to your computer and use it in GitHub Desktop.
Save schmohlio/c0df1859ad18b65cedb51fac3258bafe to your computer and use it in GitHub Desktop.
Text Editor Buffer with 2 Stacks (Sedgewick Algorithms) Example
public class GapBuffer {
private final Stack<Char> left, right;
private final int n;
public GapBuffer() {
left = new Stack<>();
right = new Stack<>();
n = 0;
}
public GapBuffer(char[] existing) {
this();
for (char c : existing) {
left.push(c);
}
}
public void insert(char c) {
left.push(c);
n++;
}
public char get() {
return left.peek();
}
public char delete() {
char c = left.pop();
n--;
return c;
}
public void left(int k) {
while (k-- > 0 && !left.empty()) {
right.push(left.pop());
}
}
public void right(int k) {
while (k-- > 0 && !right.empty()) {
left.push(right.pop());
}
}
public int size() {
return n;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment