Java 为什么要采用这种解决方案;克隆带有下一个随机指针的链接列表;O(1)是空间复杂性吗?

Java 为什么要采用这种解决方案;克隆带有下一个随机指针的链接列表;O(1)是空间复杂性吗?,java,data-structures,linked-list,big-o,space-complexity,Java,Data Structures,Linked List,Big O,Space Complexity,给定一个链表,每个节点中有两个指针。第一个指针指向列表的下一个节点,另一个指针是随机的,可以指向列表的任何节点。编写一个在O(1)空间中克隆给定列表的程序,即不使用任何额外空间 答案如下: 在每个节点之间插入copyNode 然后将随机指针复制到原始->下一步(即复制的指针) 解决方案: /** * Definition for singly-linked list with a random pointer. * class RandomListNode { * int labe

给定一个链表,每个节点中有两个指针。第一个指针指向列表的下一个节点,另一个指针是随机的,可以指向列表的任何节点。编写一个在O(1)空间中克隆给定列表的程序,即不使用任何额外空间

答案如下:

  • 在每个节点之间插入copyNode
  • 然后将随机指针复制到原始->下一步(即复制的指针)
  • 解决方案:

    /**
     * Definition for singly-linked list with a random pointer.
     * class RandomListNode {
     *     int label;
     *     RandomListNode next, random;
     *     RandomListNode(int x) { this.label = x; }
     * };
     */
    public class Solution {
        /**
         * @param head: The head of linked list with a random pointer.
         * @return: A new head of a deep copy of the list.
         */
        public RandomListNode copyRandomList(RandomListNode head) {
            RandomListNode cur = head;
            //insert copy in between nodes
            while(cur != null)
            {
                RandomListNode copy = new RandomListNode(cur.label);
                //1->1'->2
                copy.next = cur.next;
                cur.next = copy;
                cur = cur.next.next;
            }
            cur = head;
            //assign random to copy
            while(cur != null)
            {
                RandomListNode copy = cur.next;
                //random.next is the copy of random
                if(cur.random != null)
                {
                    copy.random = cur.random.next;
                }
                cur = cur.next.next;
            }
    
            RandomListNode dummy = new RandomListNode(0);
            cur = head;
            RandomListNode copyPre = dummy;
    
            while(cur != null)
            {
                RandomListNode copyNode = cur.next;
                //split and reconnect w/ original next node
                cur.next = copyNode.next;
                //connect the copied node
                copyPre.next = copyNode;
                copyPre = copyNode; //iterates copy
                cur = cur.next; //iterates
            }
    
            return dummy.next;
        }
    }
    
    现在,我看到副本正在创建新的额外空间。看起来像是空格:O(N)


    有人能解释为什么这是空间:O(1)?

    除了原始源数据(O(n))和结果数据(也就是O(n)),算法只使用O(1)辅助数据。

    我想他的意思是,除了复制的数据,辅助数据应该只占用O(1)空间。请直接在问题中放入代码或伪代码。用英语描述一个算法可能非常含糊。此外,关于这方面的问题应该是独立的。否则,如果有一天超链接消失了,你的问题对未来的读者来说将是不可理解的。@Hoblovski谢谢你的回答,你能解释一下辅助词是如何占据O(1)的吗?是因为链表一次只指向一个空间吗?@YongdingLiu除了复制的节点外,算法使用了哪个辅助空间?否则这个问题就没有意义了。任何生成克隆的算法当然都需要克隆本身的O(n)空间。