use of CtCILibrary.LinkedListNode in project ctci by careercup.
the class Question method deleteDupsB.
public static void deleteDupsB(LinkedListNode head) {
if (head == null)
return;
LinkedListNode current = head;
while (current != null) {
/* Remove all future nodes that have the same value */
LinkedListNode runner = current;
while (runner.next != null) {
if (runner.next.data == current.data) {
runner.next = runner.next.next;
} else {
runner = runner.next;
}
}
current = current.next;
}
}
use of CtCILibrary.LinkedListNode in project ctci by careercup.
the class Question method deleteDupsA.
public static void deleteDupsA(LinkedListNode n) {
HashSet<Integer> set = new HashSet<Integer>();
LinkedListNode previous = null;
while (n != null) {
if (set.contains(n.data)) {
previous.next = n.next;
} else {
set.add(n.data);
previous = n;
}
n = n.next;
}
}
use of CtCILibrary.LinkedListNode in project ctci by careercup.
the class Question method main.
public static void main(String[] args) {
/* Create linked list */
int[] vals = { 1, 3, 7, 5, 2, 9, 4 };
LinkedListNode head = new LinkedListNode(vals[0], null, null);
LinkedListNode current = head;
for (int i = 1; i < vals.length; i++) {
current = new LinkedListNode(vals[i], null, current);
}
System.out.println(head.printForward());
/* Partition */
LinkedListNode h = partition(head, 5);
/* Print Result */
System.out.println(h.printForward());
}
use of CtCILibrary.LinkedListNode in project ctci by careercup.
the class Question method partition.
public static LinkedListNode partition(LinkedListNode node, int x) {
LinkedListNode beforeStart = null;
LinkedListNode beforeEnd = null;
LinkedListNode afterStart = null;
LinkedListNode afterEnd = null;
/* Partition list */
while (node != null) {
LinkedListNode next = node.next;
node.next = null;
if (node.data < x) {
if (beforeStart == null) {
beforeStart = node;
beforeEnd = beforeStart;
} else {
beforeEnd.next = node;
beforeEnd = node;
}
} else {
if (afterStart == null) {
afterStart = node;
afterEnd = afterStart;
} else {
afterEnd.next = node;
afterEnd = node;
}
}
node = next;
}
/* Merge before list and after list */
if (beforeStart == null) {
return afterStart;
}
beforeEnd.next = afterStart;
return beforeStart;
}
use of CtCILibrary.LinkedListNode in project ctci by careercup.
the class QuestionA method addLists.
private static LinkedListNode addLists(LinkedListNode l1, LinkedListNode l2, int carry) {
if (l1 == null && l2 == null && carry == 0) {
return null;
}
LinkedListNode result = new LinkedListNode();
int value = carry;
if (l1 != null) {
value += l1.data;
}
if (l2 != null) {
value += l2.data;
}
result.data = value % 10;
if (l1 != null || l2 != null) {
LinkedListNode more = addLists(l1 == null ? null : l1.next, l2 == null ? null : l2.next, value >= 10 ? 1 : 0);
result.setNext(more);
}
return result;
}
Aggregations