判断两个链表是否存在交点 并求出位置

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yyyCHyzzzz/article/details/63684198
private static class Node {
	private int value;
	private Node next;

	public Node(int value) {
		this.value = value;
	}
	//省略get set
}
public static Node checkNodeIntersect(Node node1, Node node2) {
	if (node1 == null && node2 == null) {
		return null;
	}
	int n1Num = 0;
	int n2Num = 0;
	int subTract = 0;
	Node n1 = node1;
	Node n2 = node2;
	int diff = 0;

	// 分别得到两段链表长度 得到最后一个节点
	while (n1.next != null) {
		n1Num++;
		n1 = n1.next;
	}
	while (n2.next != null) {
		n2Num++;
		n2 = n2.next;
	}

	// 如果最后的一个节点不相同 则返回null
	if (n1 != n2) {
		return null;
	}
	// 得到两个链表的差
	diff = Math.abs(n1Num - n2Num);

	// 比较两段链表的长度,长的为n1 短的为n2
	if (n1Num > n2Num) {
		n1 = node1;
		n2 = node2;
	} else {
		n1 = node2;
		n2 = node1;
	}

	// 把长的一段移动diff位置 使得与另一段链表相等起始位置
	for (int i = 0; i < diff; i++) {
		n1 = n1.next;
	}
	// 遍历到n1 == n2时(比较地址)结束遍历
	while (n1 != n2) {
		n1 = n1.next;
		n2 = n2.next;
	}
	// 返回相交节点
	return n1;
}

测试:

public static void main(String[] args) {
	Node node1 = new Node(1);
	node1.next = new Node(2);
	Node diff = new Node(3);
	node1.next.next = diff;
	Node node2 = new Node(11);
	node2.next = new Node(22);
	node2.next.next = diff;
	System.out.println(checkNodeIntersect(node1, node2).getValue());
}

先将两段链表长度相减 长度长的那一个链表移动相减的长度 然后再遍历比较 最后得到相交的节点

网上的拓展还有很多情况,比如链表成环,等等。。

猜你喜欢

转载自blog.csdn.net/yyyCHyzzzz/article/details/63684198
今日推荐