package com.zmz.algorithm.listnode;
import java.util.List;
/**
* @author 张明泽
* Create by 2022/5/29 15:39
* 链表相交
* 面试题02.07=链表相交
*/
public class ListIntersection {
public static void main(String[] args) {
ListNode head1 = new ListNode(4);
ListNode node2 = new ListNode(1);
ListNode node3 = new ListNode(8);
ListNode node4 = new ListNode(4);
ListNode node5 = new ListNode(5);
head1.next = node2;
node2.next = node3;
node3.next = node4;
node4.next = node5;
ListNode head11 = new ListNode(5);
ListNode node22 = new ListNode(0);
ListNode node33 = new ListNode(1);
head11.next = node22;
node22.next = node33;
node33.next = node3;
node3.next = node4;
node4.next = node5;
ListNode result = interSection(head1,head11);
traverse(result);
}
/**
* 让长的先走完长度差(这样就并排一起走)
*/
public static ListNode interSection(ListNode listNodeA, ListNode listNodeB) {
ListNode headA = listNodeA;
ListNode headB = listNodeB;
int sizeA = 0;
int sizeB = 0;
// 分别求长度
while (headA != null) {
sizeA++;
headA = headA.next;
}
while (headB != null) {
sizeB++;
headB = headB.next;
}
// 重新指向首节点
headA = listNodeA;
headB = listNodeB;
int difference = Math.abs(sizeA - sizeB);
// 让长的走个差值 这样可以达到并排走的效果
for (int i = 0; i < difference; i++) {
if (sizeA > sizeB) {
headA = headA.next;
} else if (sizeA < sizeB){
headB = headB.next;
}
}
while (headA != null) {
if (headA == headB) {
return headA;
}
headA = headA.next;
headB = headB.next;
}
return null;
}
public static class ListNode {
int val;
ListNode next;
ListNode() {}
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
public static void traverse(ListNode listNode) {
while (listNode != null) {
System.out.println(listNode.val);
listNode = listNode.next;
}
}
}
最后修改:2022 年 05 月 29 日 10 : 21 PM
© 允许规范转载