LeetCode 141. 环形链表

给定一个链表,判断链表中是否有环。

进阶:
你能否不使用额外空间解决此题?

//思路:

//设置快慢指针 若有换的话 ,在快指针到达链表尾之前,快指针一定会再次追上慢指针

/**
 * 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 *fast ,*slow ;
        fast = head ,slow = head;
        int time = 0 ;
        int f_step=0,s_step = 0;
        while(time != 2  )
        {
            if(fast == slow)
            {
                time ++ ;
            }
            if(fast == NULL||fast->next == NULL)
            {
                return false ;
            }
            fast = fast->next->next ;
            slow = slow->next ;
           // f_step + =2 ;
           // s_step ++ ;           
        }
        return true ;
              
    }
};

猜你喜欢

转载自blog.csdn.net/wx734518351/article/details/80247172