LeetCode142.环形链表 II(Java实现)

LeetCode链接:https://leetcode-cn.com/problems/linked-list-cycle-ii/submissions/

思路一:

同141题,快慢指针

1.链表判空

2.设置两个指针q和s,均从head开始

3.只要q不为空或者q下一跳不为空,q向后移两位,s向后移移位

4.移动过程中,如果q和s相遇,则退出3循环

5.此时q如果为空或者q的下一跳为空,说明无环,返回空节点

6.否则q接着后移,head也跟着后移,直到q和head相遇,此时q为出环结点

public class Solution {
    public ListNode detectCycle(ListNode head) {
        //1.
        if (head == null || head.next == null)
            return null;
        //2.
        ListNode q = head;
        ListNode s = head;
        //3.
        while (q != null && q.next != null) {
            q = q.next;
            q = q.next;
            s = s.next;
            //4.
            if (q == s)
                break;
        }
        //5.
        if (q == null || q.next == null)
            return null;
        //6.
        while (q != head) {
            q = q.next;
            head = head.next;
        }
        return q;
    }
}

思路二:

快慢指针问题,快指针向后一直走,慢指针每次从头走到快指针当前位置

如果慢指针在走的过程中遇见快指针,但是步数不同,则表示此处为出环点

1.链表判空

2.设置快慢指针slow和fast从head开始

3.定义count变量统计fast的移动次数

4.只要fast不为空,fast右移一位,且count++

5.fast移动后,slow每次从head开始,移动count次,如果移动过程中出现slow和fast相遇,但是步数不同,则此处出环点

6.如果4循环正常退出,则表示无环

public class Solution {
    public ListNode detectCycle(ListNode head) {   
        //1.
        if(head==null||head.next==null){
            return null;
        }
        //2.
        ListNode fast=head;
        ListNode slow=head;
        //3.
        int count=0;   
        //4.
        while(fast!=null){
            fast=fast.next;
            count++;
            //5.
            slow=head;
            for(int i=1;i<=count;i++){
                if(slow==fast&&i!=count){
                    return slow;
                }
                slow=slow.next;
            }
        }
        //6.
        return null;
    }
}

 

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值