leetcode141 Linked List Cycle(判断链表是否有环)

题目要求 (高频题)

给一个链表,判断是否有环存在。为了表示链表中的环,我们用一个整数pos来表示环的位置,如果pos等于-1,则表示没有环。

示例

**Example 1**
Input: head = [3,2,0,-4], pos = 1
Output: true
Explanation: There is a cycle in the linked list, where tail connects to the second node.

在这里插入图片描述

**Example 2**
Input: head = [1], pos = -1
Output: false
Explanation: There is no cycle in the linked list.

在这里插入图片描述

解题思路

快慢指针

判断链表中是否存在环是一类非常易考的题目,它通过“快慢”指针的技巧能够在短时间内找到链表中是否存在环。既简单又高效,只要判断快指针是否和慢指针相遇即可。

主要代码 c++

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    bool hasCycle(ListNode *head) {
        ListNode *slow = head;
        ListNode *fast = head;
        while(fast && fast->next) // 判断为空的情况
        {
            slow = slow->next;
            fast = fast->next->next; //快指针每次走两步
            if(slow==fast) return true; // 若快慢指针相遇 则有环
        }
        
        return false; //说明没环直接到末尾null,有环进while里
    }
};

相似题目

解答:leetcode876. Middle of the Linked List(寻找链表的中间元素)

原题链接:https://leetcode.com/problems/linked-list-cycle/

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值