LeetCode 解题报告 Copy List With Random Pointer

来源:互联网 发布:centos配置dhcp服务器 编辑:程序博客网 时间:2024/06/05 17:04

A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.

Return a deep copy of the list.

分析:

复杂链表的复制就是每个结点都多了一个指针,这个指针是随机指向链表中的任意结点。所以在复制过程中要考虑这个结点

整个复制过程可以分三步,第一是挨个复制每个结点,并且都链接到每个结点的后面

第二是遍历链表复制Random指针

第三是分开原始链表和新复制的链表,奇数位置的是原始链表,偶数位置的是新复制的链表

class RandomListNode{int label;RandomListNode next,random;RandomListNode(int x){this.label = x;}}public class CopyListWithRandomPointer { public RandomListNode copyRandomList(RandomListNode head) { if(head == null) return head; RandomListNode node = head; //首先复制结点,并且将其放在每个结点后面 while(node != null){ RandomListNode temp = new RandomListNode(node.label); temp.next = node.next; temp.random = null; node.next = temp; node = temp.next; } //然后复制复杂指针 node = head; while(node != null){ RandomListNode temp = node.next; if(node.random != null){ temp.random = node.random.next; } node = temp.next; } //最后将复制的结点分开,奇偶位置分开 node = head; RandomListNode CloneHead = null; RandomListNode CloneNode = null;  if(node != null){ CloneHead = CloneNode = node.next; node.next = CloneNode.next; node = node.next; } while(node != null){ CloneNode.next = node.next; CloneNode = CloneNode.next; node.next = CloneNode.next; node = node.next; } return CloneHead;  }}


0 0