題目:
現在有一個這樣的鏈表:鏈表的每一個節點都附加了一個隨機指針,隨機指針可能指向鏈表中的任意一個節點或者指向空。
請對這個鏈表進行深拷貝。
思路:
- 先將原節點進行復制
- 再將原節點的random指針進行復制
- 從鏈表中將複製的節點拆分出來
代碼:
package com.company;
public class TestNo28 {
static class RandomListNode{
int val;
RandomListNode next,random;
RandomListNode(int x){
this.val = x;
}
public String toString(){
if(this.next == null){
return String.valueOf(this.val);
}
return this.val + "->" + this.next.toString();
}
}
public static void main(String[] args) {
TestNo28 t = new TestNo28();
RandomListNode head = new RandomListNode(0);
head.next = new RandomListNode(2);
head.next.next = new RandomListNode(5);
head.next.next.next = new RandomListNode(7);
System.out.println(head);
System.out.println(t.copyRandomList(head));
}
public RandomListNode copyRandomList(RandomListNode head) {
if(head == null){
return head;
}
//對原節點進行復制
RandomListNode node = head;
while (node!= null){
RandomListNode newNode = new RandomListNode(node.val);
newNode.next =node.next;
node.next = newNode;
node = newNode.next;
}
//對原節點的Random指針進行復制
node = head;
while (node!=null){
if(node.random != null){
node.next.random = node.random.next;
}
node = node.next.next;
}
//對鏈表複製的部分進行分離
RandomListNode newHead = head.next;
node = head;
while (node!=null){
RandomListNode newNode = node.next;
node.next = newNode.next;
if(newNode.next!=null){
newNode.next = newNode.next.next;
}
node = node.next;
}
return newHead;
}
}