LeetCode 142. 环形链表 II

题目链接:LC 142. 环形链表Ⅱ


2020.10.10第一次解答:

解题思路

  1. 判断链表是否为环形链表。若是,用快慢指针返回环的长度(原理见一文搞定常见的链表问题),用于确定首个入环节点位置(末尾节点的 next 指针指向第一个入环节点)。若不是,返回0,代表链表非环形链表。
  2. 若非环形链表,返回nullptr。若为环形链表,用双指针确定首个入环节点。

C++代码

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    int isCycle(ListNode *head) {
        ListNode *slow = head;
        ListNode *fast = head;
        while (fast) {
            fast = fast->next;
            if (fast) {
                fast = fast->next;
            }
            if (fast == slow) { //获取环长度
                int cnt = 0;
                while (fast) {
                    cnt++;
                    fast = fast->next;
                    if (fast) {
                        fast = fast->next;
                    }
                    if (fast == slow) {
                        return cnt;
                    }
                slow = slow->next;
                }
            }
            slow = slow->next;
        }
        return 0;
    }

    ListNode *detectCycle(ListNode *head) {
        int length = isCycle(head);
        if (length == 0)    return nullptr;
        ListNode *slow = head;
        ListNode *fast = head;
        for (int i = 0; i <= length; i++) {
            fast = fast->next;
        }
        while (fast != slow) {
            fast = fast->next;
            slow = slow->next;
        }
        return fast;
    }
};


Java代码

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public int isCycle(ListNode head) {
        if (head == null || head.next == null)  return 0;
        ListNode slow = head;
        ListNode fast = head.next;
        while (slow != fast) {
            if (fast == null || fast.next == null)  return 0;
            slow = slow.next;
            fast = fast.next.next;
        }
        //此时已确定链表有环,进而获取环长度
        fast = fast.next;
        int cnt = 1;
        while (slow != fast) {
            fast = fast.next;
            cnt++;
        }
        return cnt;
    }

    public ListNode detectCycle(ListNode head) {
        int length = isCycle(head);
        if (length == 0)    return null;
        ListNode slow = head;
        ListNode fast = head;
        for (int i = 0; i < length; i++)    fast = fast.next;
        while (slow != fast) {
            slow = slow.next;
            fast = fast.next;
        }
        return fast;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值