求两个单链表的交点

问题

求两个单链表的交点

分析

将长的链表移动长度差的距离,然后同时移动两个链表,找到第一个相等的节点

代码

public static List<ListNode> init2IntersectionList(){
        List<ListNode> list = new ArrayList<>();
        ListNode head1 = new ListNode(0);
        ListNode head2 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        ListNode node5 = new ListNode(5);
        ListNode node6 = new ListNode(6);
        ListNode node7 = new ListNode(7);
        head1.setNext(node2);
        node2.setNext(node3);
        node3.setNext(node4);
        node4.setNext(node5);

        head2.setNext(node6);
        node6.setNext(node7);
        node7.setNext(node2);
        node2.setNext(node3);
        node3.setNext(node4);
        node4.setNext(node5);

        list.add(head1);
        list.add(head2);
        return list;
    }

public static ListNode findIntersection(ListNode head1, ListNode head2){
        int len1 = listLength(head1);
        int len2 = listLength(head2);
        if(len1 > len2){
            for(int i = 0; i < len1 - len2; i++){
                head1 = head1.getNext();
            }
        }else{
            for(int i = 0; i < len2 - len1; i++){
                head2 = head2.getNext();
            }
        }
        while(head1 != null && head2 != null && head1.getValue() != head2.getValue()){
            head1 = head1.getNext();
            head2 = head2.getNext();
        }
        return head1;
    }

    public static int listLength(ListNode head){
        if(head == null){
            return 0;
        }
        int length = 0;
        while(head != null){
            head = head.getNext();
            length++;
        }
        return length;
    }

    public static void main(String[] args) {
        List<ListNode> list = ListNode.init2IntersectionList();
        ListNode node = findIntersection(list.get(0), list.get(1));
        System.out.println( node != null ? node.getValue() : null);
     
    }

结果

2

你可能感兴趣的:(Data,structure)