Search in sources :

Example 56 with LinkedListNode

use of CtCILibrary.LinkedListNode in project CtCI-6th-Edition by careercup.

the class Tester method createLinkedList.

public static LinkedListNode createLinkedList() {
    /* Create linked list */
    int[] vals = { 3, 5, 8, 5, 10, 2, 1 };
    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);
    }
    return head;
}
Also used : LinkedListNode(CtCILibrary.LinkedListNode)

Example 57 with LinkedListNode

use of CtCILibrary.LinkedListNode in project CtCI-6th-Edition by careercup.

the class QuestionB method addLists.

private static LinkedListNode addLists(LinkedListNode l1, LinkedListNode l2) {
    int len1 = length(l1);
    int len2 = length(l2);
    if (len1 < len2) {
        l1 = padList(l1, len2 - len1);
    } else {
        l2 = padList(l2, len1 - len2);
    }
    PartialSum sum = addListsHelper(l1, l2);
    if (sum.carry == 0) {
        return sum.sum;
    } else {
        LinkedListNode result = insertBefore(sum.sum, sum.carry);
        return result;
    }
}
Also used : LinkedListNode(CtCILibrary.LinkedListNode)

Example 58 with LinkedListNode

use of CtCILibrary.LinkedListNode in project CtCI-6th-Edition by careercup.

the class QuestionA method reverseAndClone.

public static LinkedListNode reverseAndClone(LinkedListNode node) {
    LinkedListNode head = null;
    while (node != null) {
        // Clone
        LinkedListNode n = new LinkedListNode(node.data);
        n.next = head;
        head = n;
        node = node.next;
    }
    return head;
}
Also used : LinkedListNode(CtCILibrary.LinkedListNode)

Example 59 with LinkedListNode

use of CtCILibrary.LinkedListNode in project CtCI-6th-Edition 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));
}
Also used : LinkedListNode(CtCILibrary.LinkedListNode)

Aggregations

LinkedListNode (CtCILibrary.LinkedListNode)59 HashSet (java.util.HashSet)2 Stack (java.util.Stack)2