letecode [141] - Linked List Cycle
Given a linked list, determine if it has a cycle in it.
To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.
Example 1:
Input: head = [3,2,0,-4], pos = 1
Output: true
Explanation: There is a cycle in the linked list, where tail connects to the second node.
Example 2:
Input: head = [1,2], pos = 0
Output: true
Explanation: There is a cycle in the linked list, where tail connects to the first node.
Example 3:
Input: head = [1], pos = -1
Output: false
Explanation: There is no cycle in the linked list.
题目大意:
判断一个链表中是否存在环。
理 解:
设置“快”“慢”指针。“快”指针每次后移两个,“慢”指针每次后移一个,当“快”指针碰到“慢”指针,则说明存在环;若“快”指针指向空,说明不存在环。
代 码 C++:
/** * 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) { if(head==NULL) return false; ListNode * slow = head; ListNode * fast = head; while(fast!=NULL){ fast = fast->next; if(fast==slow) return true; if(fast!=NULL) fast = fast->next; if(fast==slow) return true; slow = slow->next; } return false; } };
运行结果:
执行用时 : 24 ms, 在Linked List Cycle的C++提交中击败了45.37% 的用户

浙公网安备 33010602011771号