141. The circular linked list
Leetcode: https://leetcode-cn.com/problems/linked-list-cycle/
Given a list, the list is determined whether a ring.
To show the list given ring, we integer pos connected to the end of the list to represent the position of the list (index starts from 0). If pos is -1, the ring is not on this list.
answer
Are there chain ring A, there are two cases, as shown in FIG.
A thought
Setting a second time to traverse
Has been traversed, to see whether there exists NULL, if there is no ring, or NULL if there is no overtime, there is a ring
Ideas two
Each traversal time, the address is kept down, then judge whether the current address had appeared before
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
Three ideas
Speed way pointer
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