Flatten一个LinkedList的运行时间是多少

时间:2017-02-19 19:45:40

标签: java linked-list big-o singly-linked-list

我遇到了下一个问题:

enter image description here

我的第一个想法是:时间复杂度解决方案必须是O(n),因为需要至少遍历一次。

然而,在我目前的解决方案中,我使用了两个时候。我认为这并不一定意味着指数O(n ^ 2)。你能告诉我为什么这个解决方案仍然是线性的,即使我设置了两个布尔?

class Node {
    int value;
    Node next;
    Node child;

    public Node(int val) {
        this.value = val;
    }
}

class Main {
    public static void main(String[] args) {
        Node head = generateInput1();
        flattenLinkedList(head);
        traverseLinkedList(head);
    }

    private static Node generateInput1() {
        Node n1 = new Node(1);
        Node n2 = new Node(2);
        Node n3 = new Node(3);
        Node n4 = new Node(4);
        Node n5 = new Node(5);
        Node n6 = new Node(6);
        Node n7 = new Node(7);
        Node n8 = new Node(8);
        Node n9 = new Node(9);

        n1.next = n2;
        n2.next = n3;
        n3.next = n4;
        n5.next = n6;

        n2.child = n5;
        n4.child = n7;
        n5.child = n8;
        n7.child = n9;

        return n1;
    }

    public static Node flattenLinkedList(Node head) {
        Node current = head;
        Node tail = findTail(head);

        while (current != null) {
            if (current.child != null) {
                Node head2 = current.child;
                current.child = null;
                tail.next = head2;
                tail = findTail(head2);
            }

            current = current.next;
        }

        return head;
    }

    private static Node findTail(Node x) {
        if (x == null) return x;

        while (x.next != null) {
            x = x.next;
        }
        return x;
    }

    private static void traverseLinkedList(Node h) {
        while (h != null) {
            System.out.print(h.value + " -> ");
            h = h.next;
        }
        System.out.print("NULL");
    }
}

0 个答案:

没有答案