Leetcode:Copy List with Random Pointer

来源:互联网 发布:卷皮网站源码 编辑:程序博客网 时间:2024/05/16 07:27

Copy List with Random Pointer


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.


解析:深拷贝一个链表,链表里的节点有两个指针,一个指向next一个是指向random元素。大致解法有两种:


1. 使用HashMap,记录源节点与新节点的对应关系,或者源节点与next的关系,或者源节点与random的关系。

2.直接在源节点后面复制源节点,random也是指向源节点random的next,然后分割链表即可。


代码:

/** * 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 {    public RandomListNode copyRandomList(RandomListNode head) {                if(head==null)return null;                RandomListNode dummy = new RandomListNode(0);        RandomListNode node1 = head;        RandomListNode node2 = dummy;        HashMap<RandomListNode,RandomListNode> map = new HashMap<RandomListNode,RandomListNode>();                while(node1!=null)        {            RandomListNode copynode = new RandomListNode(node1.label);            copynode.random = node1;            node2.next = copynode;            map.put(node1,node1.next);            RandomListNode tmp = node1;            node1 = node1.next;            tmp.next = copynode;            node2 = node2.next;        }                node2 = dummy.next;        while(node2!=null)        {            if(node2.random.random!=null)node2.random = node2.random.random.next;            else node2.random = null;            node2 = node2.next;        }                node1 = head;        while(node1!=null)        {            node1.next = map.get(node1);            node1 = node1.next;        }                return dummy.next;    }}




    


           ____________

           |                      |

0——>1——>2——>3——>4——>5——>null 


0 0
原创粉丝点击