feat: 2025-10-27打卡
This commit is contained in:
46
138.copy-list-with-random-pointer.java
Normal file
46
138.copy-list-with-random-pointer.java
Normal file
@@ -0,0 +1,46 @@
|
||||
/*
|
||||
* @lc app=leetcode id=138 lang=java
|
||||
*
|
||||
* [138] Copy List with Random Pointer
|
||||
*/
|
||||
|
||||
// @lc code=start
|
||||
/*
|
||||
// Definition for a Node.
|
||||
class Node {
|
||||
int val;
|
||||
Node next;
|
||||
Node random;
|
||||
|
||||
public Node(int val) {
|
||||
this.val = val;
|
||||
this.next = null;
|
||||
this.random = null;
|
||||
}
|
||||
}
|
||||
*/
|
||||
|
||||
class Solution {
|
||||
public Node copyRandomList(Node head) {
|
||||
if(head == null) {
|
||||
return null;
|
||||
}
|
||||
Map<Node, Node> ref = new HashMap<>();
|
||||
Node cur = head;
|
||||
while(cur != null) {
|
||||
Node cp = new Node(cur.val);
|
||||
ref.put(cur, cp);
|
||||
cur = cur.next;
|
||||
}
|
||||
cur = head;
|
||||
while(cur != null) {
|
||||
Node nd = ref.get(cur);
|
||||
nd.next = ref.get(cur.next);
|
||||
nd.random = ref.get(cur.random);
|
||||
cur = cur.next;
|
||||
}
|
||||
return ref.get(head);
|
||||
}
|
||||
}
|
||||
// @lc code=end
|
||||
|
||||
Reference in New Issue
Block a user