Java 展开LinkedList的运行时间是多少
我遇到了下一个问题: 我的第一个想法是:时间复杂性解决方案必须是O(n),因为需要至少遍历一次 然而,在我目前的解决方案中,我使用了两个while-bucles。我认为这并不一定意味着是指数O(n^2)。你能告诉我为什么即使我设置了两个颊,这个解决方案仍然是线性的吗Java 展开LinkedList的运行时间是多少,java,linked-list,big-o,singly-linked-list,Java,Linked List,Big O,Singly Linked List,我遇到了下一个问题: 我的第一个想法是:时间复杂性解决方案必须是O(n),因为需要至少遍历一次 然而,在我目前的解决方案中,我使用了两个while-bucles。我认为这并不一定意味着是指数O(n^2)。你能告诉我为什么即使我设置了两个颊,这个解决方案仍然是线性的吗 class Node { int value; Node next; Node child; public Node(int val) { this.value = val;
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");
}
}
欢迎来到堆栈溢出!看起来你可能在请求家庭作业帮助。虽然我们对此本身没有问题,但请注意这些,并相应地编辑您的问题。(即使这不是家庭作业,也要考虑这个建议。)如果你被允许使用线性空间,你应该能够在线性时间复杂度下完成它。你的“当前解决方案”根本不是解决方案。结果没有分类,我改变主意了。我认为解决办法确实有效。
flattLinkedList
中的主循环遍历整个列表,因此顺序为n。也有findTail
对列表的子遍历,但它们总共不超过n
。因此,我认为整个算法是线性的,只为head2
、current
和tail
指针使用恒定的空间。该算法通过设置列表的lastnext
指针来避免使用队列,因为它是构建到当前列表完成后需要处理的节点的。