141. 环形链表
Leetcode: https://leetcode-cn.com/problems/linked-list-cycle/
给定一个链表,判断链表中是否有环。
为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。
解答
链表是否有环,一种有两种情况,如下图所示
思路一
设定1秒钟时间进行遍历
一直遍历,看看是是否存在NULL的情况,如果存在就没有环,如果不存在NULL或者超时,就有环
思路二
每遍历一次,把地址存下来,就判断当前的地址是否之前出现过
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) {
set<ListNode*> buf;
ListNode* cur = head;
while(cur && cur->next) {
if(buf.find(cur) != buf.end())
return true;
buf.insert(cur);
cur = cur->next;
}
return false;
}
};
Python
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
cur = head
buf = set()
while cur and cur.next:
buf.add(cur)
if cur.next in buf:
return True
cur = cur.next
return False
思路三
快慢指针的方式
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) {
ListNode* fast = head;
ListNode* slow = head;
while(slow && fast && fast->next) {
fast = fast->next->next;
slow = slow->next;
if(fast == slow)
return true;
}
return false;
}
};
Python
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
slow = fast = head
while slow and fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow is fast:
return True
return False