019-141-Linked List Cycle 判断链表是否有环

Problem

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

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

Solution

解决方法:龟兔赛跑。快慢指针。

/**
 * 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) {
        bool is_circle = false;
        ListNode* slow = head;
        ListNode* fast = head;
        while(slow != NULL && fast !=NULL){
            slow = slow->next;
            if(fast->next != NULL){
                fast = fast->next->next;
            }else{
                break;
            }
            if(slow == fast){
                is_circle = true;
                break;
            }
        }
        return is_circle;
    }
};

解法2:使用哈希表。建立一个哈希表,从链表开始逐个访问节点,当发现有重复的节点的时候,可以判断链表为有环。

More

可以找到链表环开始的节点并返回该节点吗?参考我的博文020-142-Linked List Cycle II

你可能感兴趣的:(leetcode)