首页 > Java > java教程 > 正文

两个链表的交集

PHPz
发布: 2024-07-21 08:54:58
原创
778 人浏览过

Intersection of two LinkedLists

问题

蛮力方法:

时间复杂度:O(N+M),其中 N 和 M 是给定的两个 LinkedList 的长度。

直觉

求两个节点的长度并得到长度差
在最长的列表中向前移动两个列表的长度差,这样两个列表将从相同的长度开始。
遇到相同节点时返回。

/**
 * 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) {
        int lenA = findLength(headA);
        int lenB = findLength(headB);
        ListNode A = headA;
        ListNode B = headB;

        int diff = Math.abs(lenA-lenB);
        if(lenA > lenB){
            A = travelAhead(A,diff);
        }
        else B = travelAhead(B,diff);

        return findIntegersection(A,B);
    }
    public ListNode findIntegersection(ListNode a, ListNode b){
        while(a!=null && b!=null){
            if(a.equals(b)) return a;
            a= a.next;
            b= b.next;
        }
        return null;
    }
    public ListNode travelAhead(ListNode head, int diff){
        while(diff-->0){
            head = head.next;
        }
        return head;
    }
    public int findLength(ListNode head){
        int count = 0;
        while(head!=null){
            head = head.next;
            count++;
        }
        return count;
    }
}
登录后复制

以上是两个链表的交集的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!