Linked List Cycle

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

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

 

解法一:

使用unordered_map记录当前节点是否被访问过,如访问过说明有环,如到达尾部说明无环。

/**
 * 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) {
        unordered_map<ListNode*, bool> visited;
        while(head != NULL)
        {
            if(visited[head] == true)
                return true;
            visited[head] = true;
            head = head->next;
        }
        return false;
    }
};

【LeetCode】141. Linked List Cycle (2 solutions)

 

解法二:不使用额外空间

设置快慢指针,

fast每次前进两步,slow每次前进一步,如相遇说明有环,如到达尾部说明无环。

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

【LeetCode】141. Linked List Cycle (2 solutions)

相关文章:

  • 2021-10-04
  • 2021-07-08
  • 2021-08-08
  • 2021-09-22
  • 2022-01-06
  • 2022-03-08
  • 2022-02-11
猜你喜欢
  • 2022-01-09
  • 2021-04-23
  • 2021-09-02
  • 2021-09-14
  • 2021-12-05
  • 2022-02-02
  • 2022-01-05
相关资源
相似解决方案