Leetcode-Copy List with Random Pointer
2014-12-12 02:47
375 查看
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.
Solution:
Return a deep copy of the list.
Solution:
/** * 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) { Map<RandomListNode,RandomListNode> map = new HashMap<RandomListNode,RandomListNode>(); if (head==null) return null; RandomListNode head2 = new RandomListNode(head.label); map.put(head,head2); RandomListNode cur = head2; while (head!=null){ RandomListNode rand1 = head.random; if (rand1!=null && map.containsKey(rand1)){ cur.random = map.get(rand1); } else if (rand1!=null) { RandomListNode rand2 = new RandomListNode(rand1.label); map.put(rand1,rand2); cur.random = rand2; } if (head.next==null){ cur.next=null; } else { RandomListNode next = head.next; if (map.containsKey(next)) cur.next = map.get(next); else { RandomListNode next2 = new RandomListNode(next.label); cur.next = next2; map.put(next,next2); } } head = head.next; cur = cur.next; } return head2; } }
相关文章推荐
- Copy List with Random Pointer 复制有随机指针的链表@LeetCode
- [leetcode]Copy List with Random Pointer
- LeetCode:Copy List with Random Pointer
- LeetCode: Copy List with Random Pointer
- LeetCode — Copy List with Random Pointer 解题报告
- [LeetCode] Copy List with Random Pointer, Solution
- leetcode Copy List with Random Pointer
- LeetCode - Copy List with Random Pointer
- leetcode-Copy List with Random Pointer
- Leetcode: Copy List with Random Pointer
- LeetCode-Copy List with Random Pointer
- [LeetCode] Copy List with Random Pointer
- LeetCode:Copy List with Random Pointer
- [leetcode]Copy List with Random Pointer
- Copy List with Random Pointer [LeetCode]
- leetcode -- Copy List with Random Pointer
- LeetCode:Copy List with Random Pointer
- LeetCode(138)Copy List with Random Pointer
- [LeetCode]Copy List with Random Pointer
- leetcode - Copy List with Random Pointer