LeetCode-141. Linked List Cycle-using C/C++-判断一个链表里面是否有环

【题目描述】                              tag:Linked List                         difficulty:Easy

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

Follow up:
Can you solve it without using extra space?

即:争取不用额外空间来判断一个链表里面是否存在环

【函数形式】

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
bool hasCycle(struct ListNode *head)
{
}

【解题思路】

刚开始想的,可以用计数遍历的方法,设一个最大遍历次数,如果超过这个数或者遍历到NULL,那么不在遍历链表,结果提交之后显示运行超时,所以这个想法不可行。

接下来想到:如果在一个环里边遍历,那么一个一个挨个遍历的指针与隔一个一遍历的指针早晚会相遇。于是产生了一个可行方案:初始化两个指针,初始状态下分别指向链表头,其中一个逐个遍历下去,另一个指针隔一个一遍历,两指针如果在之后的遍历过程中相遇,那么这个链表有环,如果这两个指针遇到NULL,那么说明这个链表没环。

【代码如下】

bool hasCycle(struct ListNode *head) {
    struct ListNode* p = head;
    struct ListNode* q = head;
    if(p == NULL)
        return 0;
    if(p->next == p)
        return 1;
    q = p;
    while(p->next != NULL && q->next != NULL)
    {
        p = p->next->next;
        q = q->next;
        if(p == NULL)
            return 0;
        if(p == q)
            return 1;
    }
        return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_32549789/article/details/79580653