Linked List Cycle
1,题目要求
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.
给定一个链表,确定它是否有一个循环。
为了表示给定链表中的循环,我们使用整数pos表示tail连接到的链表中的位置(0索引)。 如果pos为-1,则链表中没有循环。
2,题目思路
这道题,是关于判断一个链表是否存在环的题目,也是比较经典的关于链表的题目。
一般这种题目,使用到的思路便是比较有名的快慢指针法:
- 定义两个指针,一个是快指针(一次走两步),一个是慢指针(一次走一步)
- 如果链表不存在环,则一定是快指针先走到链表的结尾,发现了空节点。
- 而如果链表存在环,则快指针一定会先进入环,之后,慢指针变成了在快指针前面,因此,快指针最后一定可以追上慢指针,即二者一定会相遇。
还有另外一种策略,就是对遍历过的链表的值进行修改。这样也可以很快判断一个链表是否有环,但是会修改原链表。
3,代码实现
1,快慢指针
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
int x = []() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
return 0;
}();
class Solution {
public:
bool hasCycle(ListNode *head) {
if(head == nullptr)
return false;
ListNode *slow = head;
ListNode *fast = head;
while(fast != nullptr && fast->next != nullptr){
fast = fast->next->next;
slow = slow->next;
if(fast == slow)
return true;
}
return false;
}
};
2,修改链表
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
int x = []() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
return 0;
}();
class Solution {
public:
bool hasCycle(ListNode *head) {
if(head == NULL)
return false;
while(head->next != NULL)
{
head->val = INT_MAX;
if(head->next->val == INT_MAX)
return true;
head = head->next;
}
return false;
}
};