leetcode题目
copy-list-with-random-pointer
题目描述
* 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.
思路
* 1、复制next指针,复制链表的每一个节点,放在每个源节点的后面,源节点的next指针指向复制出来的节点
* 2、复制random指针,复制的节点,复制他的前一个节点的random指针
* 3、拆分链表,取偶数序号的元素组成新的链表
代码
package com.leetcode.list;
/**
* 题目:
* copy-list-with-random-pointer
*
* 题目描述:
*
* 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.
*/
public class CopyComplexList {
static class RandomListNode {
int label;
RandomListNode next, random;
RandomListNode(int x) { this.label = x; }
@Override
public String toString() {
if (this.next == null) {
return String.valueOf(this.label);
}
return this.label + "(" +(this.random==null?"":this.random.label) + ")"
+ "->" + this.next.toString();
}
};
/**
* 思路:
* 1、复制next指针,复制链表的每一个节点,放在每个源节点的后面,源节点的next指针指向复制出来的节点
* 2、复制random指针,复制的节点,复制他的前一个节点的random指针
* 3、拆分链表,取偶数序号的元素组成新的链表
*
* @param head 头节点
*/
public RandomListNode copyRandomList(RandomListNode head) {
if (head == null) {
return null;
}
// 1、复制节点,放在源节点后面
RandomListNode cur = head;
while (cur != null) {
// 缓存下一个节点
RandomListNode next = cur.next;
// copy next指针即节点的值
RandomListNode copy = new RandomListNode(cur.label);
cur.next = copy;
copy.next = next;
// cur指向下一个节点
cur = next;
}
// 2、复制random指针
cur = head;
while (cur != null && cur.next != null) {
RandomListNode node = cur.random;
if (node != null) {
cur.next.random = node.next;
}
cur = cur.next.next;
}
// 3、取偶数序号的元素组成链表
RandomListNode newHead = head.next;
cur = newHead;
while (cur != null && cur.next != null) {
cur.next = cur.next.next;
cur = cur.next;
}
return newHead;
}
public static void main(String[] args) {
RandomListNode head = createTestLinkedList();
RandomListNode newHead = new RandomListNode(13);
newHead.next = head;
head.random = head.next.next;
System.out.println(newHead);
System.out.println(new CopyComplexList().copyRandomList(newHead));
}
private static RandomListNode createTestLinkedList() {
RandomListNode head = new RandomListNode(0);
RandomListNode curNode = head;
for (int i = 1; i < 10; i++) {
curNode.next = new RandomListNode(i);
curNode = curNode.next;
}
return head;
}
}