【简单算法】25. 环形链表

题目:

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

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

解题思路:

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;
        }
    }
};

猜你喜欢

转载自www.cnblogs.com/mikemeng/p/8985075.html