class Solution { public Node copyRandomList(Node head) { if (head == null) { return head; } //将拷贝节点放到原节点后面,例如1->2->3这样的链表就变成了这样1->1'->2->2'->3->3' // 即复制原有结点并接在原有链表后面 Node cur = head; while(cur != null){ Node copy = new Node(cur.val); copy.next = cur.next; cur.next = copy; cur = cur.next.next; } // 复制随机结点 Node cur2 = head; while(cur2 != null){ if (cur2.random != null) cur2.next.random = cur2.random.next; cur2 = cur2.next.next; } //分离拷贝节点和原节点,变成1->2->3和1'->2'->3'两个链表,后者就是答案 Node cur3 = head, dummy = head.next; while(cur3 != null && cur3.next != null){ Node temp = cur3.next; cur3.next = temp.next; cur3 = temp; } return dummy; } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)