java实现---判断两个链表是否相交,若相交,求交点(假设链表不带环)

有两个单链表,判断它们是否相交,若相交,求交点

第一步判断两个链表是否相交

  • 如果两个链表相交,那么它们的最后一个节点肯定是同一个节点,如下图展示
    在这里插入图片描述

  • 我们可以分别遍历两个链表,直到最后一个节点

  • 当最后两个是同一个节点时,则说明相交

 public static boolean IsPoint(ListNode first,ListNode head){
        
        ListNode forward = first;
        ListNode backward = head;
        if((first == null)||(head == null)){
            return false;
        }
        while(first != null){
            first = first.next;
        }
        while(head != null){
            head = head.next;
        }
        return first == head;
    }
  • 当返回值为true时,则说明相交

第二步求交点

  • 先求出两个链表的长度
  • 当两个等长时,则两个节点同时往后走,当走到同一个时,返回该节点,则为交点
  • 当不等长时,首先求出长度之差diff,然后让长的链表先走diff步,接着,两个同时走,走到同一个时,返回其中一个节点,则为交点
public class Link{
    public static int Length(ListNode list){  //求两个链表的长度
        int count = 0;
        while(list != null){
            list = list.next;
            count++;
        }
        return count;

    }
    public static ListNode Point(ListNode list1,ListNode list2){
        int len1 = Length(list1);         
        int len2 = Length(list2);
        ListNode longL = list1;
        ListNode shortL = list2;
        int diff = len1 -len2;
        if(len2 > len1){
             longL = list2;
             shortL = list1;
             diff = len2 -len1;
        }                                                //长的链表定为longL遍历    短的shortL遍历
            while(diff-- != 0){
            longL = longL.next;
        }
        while(true){
            if(longL == shortL){
                return longL;
            }
            longL = longL.next;
            shortL = shortL.next;
        }
    }

  • 测试
//    public static void main(String[] args) {
//        ListNode n1 = new ListNode();
//        ListNode n2 = new ListNode();
//        ListNode n3 = new ListNode();
//        ListNode n4 = new ListNode();
//        n1.data = 2;
//        n2.data = 2;
//        n3.data = 3;
//        n4.data = 4;
//        n1.next = n2;
//        n2.next = n3;
//        n3.next = n4;
//        ListNode n5 = new ListNode();
//        ListNode n6 = new ListNode();
//        ListNode n7 = new ListNode();
//        ListNode n8 = new ListNode();
//        n5.data = 1;
//        n6.data = 2;
//        n7.data = 7;
//        n8.data = 8;
//        n5.next = n6;
//        n6.next = n7;
//        n7.next = n8;
//        
    IsPoint(n1,n5);
//    }
//}

猜你喜欢

转载自blog.csdn.net/WZL995/article/details/84677141