2025年- H21-Lc129-160. 相交链表(链表)---java版
1.题目描述
2.思路
当pa!=pb的时候,执行pa不为空,遍历pa链表。执行pb不为空,遍历pb链表。
3.代码实现
// 单链表节点定义
class ListNode {int val;ListNode next;ListNode(int x){val=x;next=null;}}public class H160 {// 主方法:找出两个链表的交点public ListNode getIntersectionNode(ListNode headA, ListNode headB) {if(headA==null||headB==null){return null;}ListNode Pa=headA;ListNode Pb=headB;while(Pa!=Pb) {if (Pa != null) {Pa = Pa.next;} else {Pa = headB;}if (Pb != null) {Pb = Pb.next;} else {Pb = headA;}}return Pa;}//测试用例public static void main(String[] args) {// 公共部分:相交的部分ListNode common = new ListNode(8);common.next = new ListNode(10);// 链表 A:4 -> 1 -> 8 -> 10ListNode headA = new ListNode(4);headA.next = new ListNode(1);headA.next.next = common;// 链表 B:5 -> 6 -> 1 -> 8 -> 10ListNode headB = new ListNode(5);headB.next = new ListNode(6);headB.next.next = new ListNode(1);headB.next.next.next = common;// 测试H160 solution = new H160();ListNode intersection = solution.getIntersectionNode(headA, headB);if (intersection != null) {System.out.println("交点值为:" + intersection.val);} else {System.out.println("没有交点。");}}
}