链表环,相交链表

一个链表存表,如果存在环,则返回入环节点,否则返回null

快慢指针 相遇即是 入环节点 (快慢指针可以求中点)

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode detectCycle(ListNode head) {
        if(head==null ){
            return null;
        }
        ListNode slow=head;
        ListNode fast=head;
        while(slow!=null && fast!=null){
            slow=slow.next;
            fast=fast.next;
            if(fast==null){
                return null;
            }else{
                fast=fast.next;
            }
            if(slow==fast){
                break;
            }
        }
        if(fast==null){
            return null;
        }
        ListNode ptr=head;//第三个指针
        while(ptr!=slow){
            ptr=ptr.next;
            slow=slow.next;
        }
        return ptr;
    }
}

两个链表,如果相交,则返回相交点,否则返回null

方法1

求链表长度,然后根据长度差值,用两个指针遍历看是否会相遇

public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        int lenA=0,lenB=0;
        ListNode pa=headA,pb=headB;
        while(pa!=null){
            pa=pa.next;
            lenA++;
        }
        while(pb!=null){
            pb=pb.next;
            lenB++;
        }
        if(lenA==0 || lenB==0){
            return null;
        }
        ListNode s=headA,l=headB;
        if(lenA>lenB){
            l=headA;
            s=headB;
        }
        for(int i=0;i<Math.abs(lenB-lenA);i++){
                l=l.next;
        }
        while(s!=null && l!=null){
            if(s==l){
                return s;
            }
            s=s.next;
            l=l.next;
        }
        return null;
    }
方法2

两个指针,依次遍历两个链表

ublic ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        ListNode p1=headA;
        ListNode p2=headB;

        if(p1==null || p2==null){
            return null;
        }
        while(p1!=null && p2!=null){
            if(p1==p2){
                return p1;
            }
            p1=p1.next;
            p2=p2.next;
            if(p1==null){
                p1=headB;
            }else if(p2==null){
                p2=headA;
            }
        }
        return null;

    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值