python 带随机指针的链表深度复制_复制带随机指针的链表

题目

给出一个链表,每个节点包含一个额外增加的随机指针可以指向链表中的任何节点或空的节点。

返回一个深拷贝的链表。

解题思路

第一遍扫的时候巧妙运用next指针, 开始数组是1->2->3->4 。 然后扫描过程中 先建立copy节点 1->1'->2->2'->3->3'->4->4', 然后第二遍copy的时候去建立边的copy, 拆分节点, 一边扫描一边拆成两个链表,这里用到两个dummy node。第一个链表变回1->2->3 , 然后第二变成 1'->2'->3' 。

代码实现

/**

* 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 {

/**

* @param head: The head of linked list with a random pointer.

* @return: A new head of a deep copy of the list.

*/

//复 制 next节点

//1->2->3->4 ,变成 1->1'->2->2'->3->3'->4->4'

private void copyNext(RandomListNode head) {

while (head != null) {

RandomListNode newNode = new RandomListNode(head.label);

newNode.next = head.next;

newNode.random = head.random;

head.next = newNode;

head = head.next.next;

}

}

//复制 random

//如果1的随机指针指向2,则复制1'的随机指针指向2',

private void copyRandom(RandomListNode head) {

while (head != null) {

if (head.next.random != null) {

head.next.random = head.random.next;

}

head = head.next.next;

}

}

//拆 分

// 1->1'->2->2'->3->3'->4->4' 变成 1->2->3->4和1'->2'->3'->4'

private RandomListNode spiltList(RandomListNode head) {

RandomListNode newHead = head.next;

while (head != null) {

RandomListNode temp = head.next;

head.next = temp.next;

head = head.next;

if (temp.next != null) {

temp.next = temp.next.next;

}

}

return newHead;

}

public RandomListNode copyRandomList(RandomListNode head) {

if (head == null) {

return null;

}

copyNext(head);

copyRandom(head);

return spiltList(head);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值