剑指offer——(26)复杂链表的复制

版权声明:本文自由转载,转载请注明出处。 https://blog.csdn.net/qq_38071429/article/details/85803974

在这里插入图片描述

参考解:chancy
参考解:C语言之复杂链表的复制(图示详解)

ac代码

public class Solution {
	
    public RandomListNode Clone(RandomListNode pHead){
    	if(pHead == null) {
    		return null;
    	}
    	// 1. 复制当前结点插到当前结点后面
    	RandomListNode head = pHead;
    	while(head != null) {
    		RandomListNode cloneNode = new RandomListNode(head.label); // 复制节点
    		cloneNode.next = head.next;
    		head.next = cloneNode;
    		head = head.next.next; // 复制节点已插入 所以需要跳过复制节点
    	}	
    	// 2. 完善复制的新节点的random指针
    	head = pHead;
    	while(head != null) {
    		// head.random.next是新结点的random 因为复制节点在旧节点的后面
    		head.next.random = head.random == null ? null : head.random.next;
    		head = head.next.next;
    	}
    	// 3. 拆分新旧链表
    	head = pHead;
    	RandomListNode result = pHead.next; // 新链表的第一个节点在旧链表的第一个节点后面
    	while(head != null) {
			RandomListNode newNode = head.next;
			head.next = newNode.next; // 旧链表
			if(newNode.next != null) { 
				newNode.next = newNode.next.next; //新链表
			}
			//newNode.next = newNode.next == null ? null : newNode.next.next; //新链表
			head = head.next;
		}
        return result;
    }
    
    public static void main(String[] args) {
    	RandomListNode Node = new RandomListNode(1);
    	RandomListNode Node2 = new RandomListNode(2);
    	RandomListNode Node3 = new RandomListNode(3);
    	RandomListNode Node4 = new RandomListNode(4);
    	Node.next = Node2;
    	Node2.next = Node3;
    	Node3.next = Node4;
    	Node4.next = null;
    	Node.random = Node3;
    	Node3.random = Node;
    	Node2.random = Node4;
    	Node4.random = Node2;   	 	   			
    	RandomListNode result = new Solution().Clone(Node);
		while(result != null) {
			System.out.println("result.label:"+result.label+" result.random.label:"+result.random.label);
			result = result.next;
		}
	}
    
}

class RandomListNode {
    int label;
    RandomListNode next = null;
    RandomListNode random = null;

    RandomListNode(int label) {
        this.label = label;
    }
}

输出:

result.label:1 result.random.label:3
result.label:2 result.random.label:4
result.label:3 result.random.label:1
result.label:4 result.random.label:2

猜你喜欢

转载自blog.csdn.net/qq_38071429/article/details/85803974