题目:

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

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

解题思路:

1.快慢指针即可,快指针每次走两步,慢指针每次走一步。快指针追上慢指针,则表示有环。

/**
 * 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 * first = head;
        ListNode * second = head;
        
        if(!head||!(head->next)){
            return  false;
        }
        
        do{
            first = first->next;
            second = second->next;
            if(second){
                second = second->next;
            }
        }while(first!=second && second && first);
            
        if(second == first && first && second){
            return true;
        }else{
            return false;
        }
    }
};

 

相关文章:

  • 2021-08-27
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2020-02-27
  • 2021-12-09
猜你喜欢
  • 2021-11-26
  • 2021-02-14
  • 2022-12-23
  • 2021-02-17
  • 2021-05-27
  • 2021-11-23
  • 2022-12-23
相关资源
相似解决方案