Intersection of Two Linked Lists

来源:互联网 发布:天津医科大学考研知乎 编辑:程序博客网 时间:2024/05/19 22:59

题意:给定两个链表,找到两个链表相交的地方
解法:遍历两个链表的长度,然后找到长链表中和短链表中长度相同的节点,开始同时遍历直到找到共同节点
复杂度:时间O(m+n),空间O(1)

public class Solution {    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {        if(headA == null || headB == null)            return null;        ListNode a = headA;        ListNode b = headB;        int lena = 0;        int lenb = 0;        while(a!=null)        {            lena++;            a=a.next;        }        while(b!=null)        {            lenb++;            b=b.next;        }        a = headA;        b = headB;        if(lena>lenb)        {            while(lena>lenb)            {                lena--;                a=a.next;            }        }        else        {            while(lenb>lena)            {                lenb--;                b=b.next;            }        }        while(a!=null&&a!=b)        {            a=a.next;            b=b.next;        }        return a;    }}
0 0