/**
* 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;
//建立一个用于遍历head的指针;
RandomListNode tempHead = head;
//建立新的list;
RandomListNode newHead = new RandomListNode(head.label);
//建立用于遍历新list的指针;
RandomListNode tempNewHead = newHead;
//建立老list与新list的对应关系;
HashMap<RandomListNode, RandomListNode> mapping = new HashMap<>();
mapping.put(tempHead, tempNewHead);
//先将所有老与新的关系放入map 再把next关系写好;
while(tempHead.next != null) {
tempNewHead.next = new RandomListNode(tempHead.next.label);
tempNewHead = tempNewHead.next;
tempHead = tempHead.next;
mapping.put(tempHead, tempNewHead);
}
//重新归于头部;
tempHead = head;
tempNewHead = newHead;
//再遍历设置一遍random
while(tempHead != null) {
tempNewHead.random = mapping.get(tempHead.random);
tempNewHead = tempNewHead.next;
tempHead = tempHead.next;
}
return newHead;
}
}
Copy List with Random Pointer leetcode java 走地牙
最新推荐文章于 2024-09-06 04:39:09 发布
这篇博客介绍了解决LeetCode中Copy List with Random Pointer问题的Java实现。通过创建新的链表并维护一个映射表,将原始链表和复制链表节点一一对应,然后遍历设置新链表的random指针。
摘要由CSDN通过智能技术生成