Linked List Cycle

406 篇文章 0 订阅
406 篇文章 0 订阅

1,题目要求

Given a linked list, determine if it has a cycle in it.

To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.

给定一个链表,确定它是否有一个循环。

为了表示给定链表中的循环,我们使用整数pos表示tail连接到的链表中的位置(0索引)。 如果pos为-1,则链表中没有循环。

在这里插入图片描述

2,题目思路

这道题,是关于判断一个链表是否存在环的题目,也是比较经典的关于链表的题目。

一般这种题目,使用到的思路便是比较有名的快慢指针法

  • 定义两个指针,一个是快指针(一次走两步),一个是慢指针(一次走一步)
  • 如果链表不存在环,则一定是快指针先走到链表的结尾,发现了空节点。
  • 而如果链表存在环,则快指针一定会先进入环,之后,慢指针变成了在快指针前面,因此,快指针最后一定可以追上慢指针,即二者一定会相遇。

还有另外一种策略,就是对遍历过的链表的值进行修改。这样也可以很快判断一个链表是否有环,但是会修改原链表。

3,代码实现

1,快慢指针

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */

int x = []() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    return 0;
}();
class Solution {
public:
    bool hasCycle(ListNode *head) {
        if(head == nullptr)
            return false;
        
        ListNode *slow = head;
        ListNode *fast = head;
    
        while(fast != nullptr && fast->next != nullptr){
            fast = fast->next->next;
            slow = slow->next;
            if(fast == slow)
                return true;
        }
        return false;
    }
};

2,修改链表

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
int x = []() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    return 0;
}();

class Solution {
public:
    bool hasCycle(ListNode *head) {
        if(head == NULL)
            return false;
        
        while(head->next != NULL)
        {
            head->val = INT_MAX;
            if(head->next->val == INT_MAX)
                return true;
            head = head->next;
        }
        return false;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值