Intersection of Two Linked Lists

来源:互联网 发布:dns的默认端口 编辑:程序博客网 时间:2024/06/18 08:09
/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { *         val = x; *         next = null; *     } * } */public class Solution {    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {        if (headA == null || headB == null) {            return null;        }        ListNode p1 = headA, p2 = headB;        ListNode tail1 = null, tail2 = null;        while (true) {            if (p1 == null) {                p1 = headB;            }            if (p2 == null) {                p2 = headA;            }            if (p1.next == null) {                tail1 = p1;            }            if (p2.next == null) {                tail2 = p2;            }            if (tail1 != null && tail2 != null && tail1 != tail2) {                return null;            }            if (p1 == p2) {                return p1;            }            p1 = p1.next;            p2 = p2.next;        }            }}

0 0
原创粉丝点击