在有环单链表中找公共部分

目录

题目描述:

解法:


题目描述:

给你两个有环单链表的头节点 head1 和 head2,入环结点分别为loop1,loop2,请你找出并返回两个单链表相交的起始节点(如果有两个,则返回任意一个)。如果两个链表不存在相交节点,返回 null。

解法:

class ListNode {
      int val;
      ListNode next;
      ListNode() {}
      ListNode(int val) { this.val = val; this.next = null; }
      ListNode(int val, ListNode next) { this.val = val; this.next = next; }
  }  

    public ListNode getIntersectionNode(ListNode head1, ListNode loop1, ListNode head2,                         ListNode loop2){
        if(head1==null || head2==null){
            return null;
        }
        if(loop1==loop2){
            ListNode cur1 = head1;
            ListNode cur2 = head2;
            int n = 0;
            while(cur1!=loop1){
                cur1 = cur1.next;
                n++;
            }
            while(cur2!=loop2){
                cur2 = cur1.next;
                n--;
            }
            cur1 = n > 0 ? head1 : head2;
            cur2 = cur1 == head1 ? head2 : head1;
            n = Math.abs(n);
            while(n!=0){
                cur1 = cur1.next;
            }
            while(cur1!=cur2){
                cur1 = cur1.next;
                cur2 = cur2.next;
            }
            return cur1;
        }else{
            ListNode cur1 = loop1.next;
            while(cur1!=loop1){
                if(cur1==loop2){
                    return loop2;
                }
                cur1 = cur1.next;
            }
            return null;
        }
    }

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值