AcWing 48. 复杂链表的复刻
原题链接
中等
作者:
小轩喵灬
,
2025-01-11 15:15:40
,
所有人可见
,
阅读 1
/**
* Definition for singly-linked list with a random pointer.
* class ListNode {
* int val;
* ListNode next, random;
* ListNode(int x) { this.val = x; }
* };
*/
class Solution {
public ListNode copyRandomList(ListNode head) {
if (head == null) {
return null;
}
//后部插入新节点
ListNode cur = head;
while(cur != null) {
ListNode listNode = new ListNode(cur.val);
listNode.next = cur.next;
cur.next = listNode;
cur = listNode.next;
}
// 建立random链接
cur = head;
while(cur != null) {
ListNode clone = cur.next;
if (cur.random != null) {
clone.random = cur.random.next;
}
cur = clone.next;
}
//拆分
cur = head;
ListNode cloneHead = head.next;
while(cur.next != null) {
ListNode next = cur.next;
cur.next = next.next;
cur = next;
}
return cloneHead;
}
}