Skip to content

Instantly share code, notes, and snippets.

@tippenein
Created March 8, 2013 01:24
Show Gist options
  • Save tippenein/5113504 to your computer and use it in GitHub Desktop.
Save tippenein/5113504 to your computer and use it in GitHub Desktop.
linked list questions
//return the nth to last item in a linked list
public static void nthToLast(LinkedListNode n, Integer i) {
LinkedListNode p1 = n;
LinkedListNode p2 = n;
// just iterate p2 for i steps and wait for it to hit null
while (i != 0) {
p2 = p2.next;
i--;
}
while (p2 != null) {
p1 = p1.next;
p2 = p2.next;
}
return p1.data
}
// remove duplicates from a linked list
public static void removeDups(LinkedListNode n) {
HashTable t = new HashTable<Integer, Boolean>();
LinkedListNode previous = null;
while (n != null) {
if (t.containsKey(n.data)) {
previous = n.next
} else {
t.put(n.data, true);
previous = n;
}
n = n.next;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment