use of CtCILibrary.LinkedListNode in project ctci by careercup.
the class QuestionB method isPalindrome.
public static boolean isPalindrome(LinkedListNode head) {
LinkedListNode fast = head;
LinkedListNode slow = head;
Stack<Integer> stack = new Stack<Integer>();
while (fast != null && fast.next != null) {
stack.push(slow.data);
slow = slow.next;
fast = fast.next.next;
}
/* Has odd number of elements, so skip the middle */
if (fast != null) {
slow = slow.next;
}
while (slow != null) {
int top = stack.pop().intValue();
System.out.println(slow.data + " " + top);
if (top != slow.data) {
return false;
}
slow = slow.next;
}
return true;
}
use of CtCILibrary.LinkedListNode in project ctci by careercup.
the class QuestionB method main.
public static void main(String[] args) {
int length = 9;
LinkedListNode[] nodes = new LinkedListNode[length];
for (int i = 0; i < length; i++) {
nodes[i] = new LinkedListNode(i >= length / 2 ? length - i - 1 : i, null, null);
}
for (int i = 0; i < length; i++) {
if (i < length - 1) {
nodes[i].setNext(nodes[i + 1]);
}
if (i > 0) {
nodes[i].setPrevious(nodes[i - 1]);
}
}
//nodes[length - 2].data = 9; // Uncomment to ruin palindrome
LinkedListNode head = nodes[0];
System.out.println(head.printForward());
System.out.println(isPalindrome(head));
}
use of CtCILibrary.LinkedListNode in project ctci by careercup.
the class Question method deleteDupsC.
public static void deleteDupsC(LinkedListNode head) {
if (head == null)
return;
LinkedListNode previous = head;
LinkedListNode current = previous.next;
while (current != null) {
// Look backwards for dups, and remove any that you see.
LinkedListNode runner = head;
while (runner != current) {
if (runner.data == current.data) {
LinkedListNode tmp = current.next;
previous.next = tmp;
current = tmp;
/* We know we can't have more than one dup preceding
* our element since it would have been removed
* earlier. */
break;
}
runner = runner.next;
}
/* If runner == current, then we didn't find any duplicate
* elements in the previous for loop. We then need to
* increment current.
* If runner != current, then we must have hit the �break�
* condition, in which case we found a dup and current has
* already been incremented.*/
if (runner == current) {
previous = current;
current = current.next;
}
}
}
use of CtCILibrary.LinkedListNode in project ctci by careercup.
the class Question method main.
public static void main(String[] args) {
LinkedListNode head = AssortedMethods.randomLinkedList(10, 0, 10);
System.out.println(head.printForward());
// delete node 4
deleteNode(head.next.next.next.next);
System.out.println(head.printForward());
}
use of CtCILibrary.LinkedListNode in project ctci by careercup.
the class Question method deleteNode.
public static boolean deleteNode(LinkedListNode n) {
if (n == null || n.next == null) {
// Failure
return false;
}
LinkedListNode next = n.next;
n.data = next.data;
n.next = next.next;
return true;
}
Aggregations