复杂链表的复制(Java实现)

该题为剑指offer面试题26


牛客网测试地址:https://www.nowcoder.com/questionTerminal/f836b2c43afc4b35ad6adc41ec941dba


  • 热度指数:70797  
    时间限制:1秒  空间限制:32768K
  • 算法知识视频讲解
输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)


package go.jacob.day430;

public class Demo1 {
	public RandomListNode Clone(RandomListNode pHead) {
		createDoubleNode(pHead);

		connectRandomNode(pHead);

		RandomListNode newHead = ReconnectNodes(pHead);
		return newHead;

	}

	/*
	 * 复制节点,把新建的节点A‘连接在原节点A后
	 */
	private void createDoubleNode(RandomListNode pHead) {
		RandomListNode tmpNode = pHead;
		while (tmpNode != null) {
			RandomListNode node = new RandomListNode(tmpNode.label);
			node.next = tmpNode.next;
			tmpNode.next = node;
			tmpNode = node.next;
		}
	}

	/*
	 * 链接random节点,eg. 在原链表中A的random是B,那么在新链表中,A’链接B‘
	 */
	private void connectRandomNode(RandomListNode pHead) {
		RandomListNode tmpNode = pHead;
		while (tmpNode != null) {
			if (tmpNode.random != null) {
				RandomListNode node = tmpNode.next;
				node.random = tmpNode.random.next;
				tmpNode = node.next;
			} else {
				tmpNode = tmpNode.next.next;
			}
		}
	}

	/*
	 * 把两个相连的链表拆分成两个
	 */
	private RandomListNode ReconnectNodes(RandomListNode pHead) {
		if (pHead == null)
			return null;
		RandomListNode tmpNode = pHead;
		RandomListNode newHead = pHead.next;

		while (tmpNode != null) {
			RandomListNode node = tmpNode.next;
			tmpNode.next = node.next;
			if (node.next != null)
				node.next = node.next.next;
			else
				node.next = null;
			tmpNode = tmpNode.next;
		}

		return newHead;
	}

	// 节点类
	public class RandomListNode {
		int label;
		RandomListNode next = null;
		RandomListNode random = null;

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



你可能感兴趣的:(剑指offer(Java实现))