Created
January 14, 2019 00:44
-
-
Save schmohlio/c0df1859ad18b65cedb51fac3258bafe to your computer and use it in GitHub Desktop.
Text Editor Buffer with 2 Stacks (Sedgewick Algorithms) Example
This file contains 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
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