Skip to content

Instantly share code, notes, and snippets.

@nm3mon
Created August 16, 2013 15:38
Show Gist options
  • Save nm3mon/6250965 to your computer and use it in GitHub Desktop.
Save nm3mon/6250965 to your computer and use it in GitHub Desktop.
Remove some chars from a singly-linked list of chars using a backtracker.
class BacktrackingCharFiltering {
static class Node<E> {
Node<E> next;
E data;
Node(E data) {
this.data = data;
}
}
static class List<E> {
Node<E> head;
Node<E> tail;
//inserts at tail
void insert(Node<E> newNode) {
if (head == null) {
head = newNode;
tail = newNode;
}
else {
tail.next = newNode;
tail = newNode;
}
}
List<E> remove(Set<E> rLetters) {
Node<E> backTracker = null;
Node<E> nodePtr = head;
while (nodePtr != null) {
if (rLetters.contains(nodePtr.data)) {
if (backTracker != null) { //we're ahead in list
backTracker.next = nodePtr.next;
nodePtr = nodePtr.next;
}
else { //we're on the head
head = nodePtr.next;
nodePtr = head;
}
}
else {
backTracker = nodePtr;
nodePtr = nodePtr.next;
}
}
return this;
}
}
public static void main(String[] args) {
List<Character> letters = new List<>();
Set<Character> rLetters = new HashSet<>();
String rString = "strwk";
for (int i = 0; i < rString.length(); i++) {
rLetters.add(rString.charAt(i));
}
String word = "star trek: wrath of khan";
for (int i = 0; i < word.length(); i++) {
letters.insert(new Node<>(word.charAt(i)));
}
letters.remove(rLetters);
Node<Character> begin = letters.head;
while (begin != null) {
System.out.print(begin.data + " --> ");
begin = begin.next;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment