141. Linked List Cycle
2017-10-10 20:26
330 查看
Given a linked list, determine if it has a cycle in it.
这个题目记住就可以,没做过的还真不一定能想到
java
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public boolean hasCycle(ListNode head) {
if (head == null || head.next == null) {
return false;
}
ListNode slow = head;
ListNode fast = head.next;
while (true) {
if (fast.next == null || fast.next.next == null) {
return false;
}
if (slow == fast) {
return true;
}
fast = fast.next.next;
slow = slow.next;
}
}
}
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
"""
if head is None or head.next is None:
return False
slow, fast = head, head.next
while True:
if fast.next is None or fast.next.next is None:
return False
if slow is fast:
return True
slow = slow.next
fast = fast.next.next
这个题目记住就可以,没做过的还真不一定能想到
java
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public boolean hasCycle(ListNode head) {
if (head == null || head.next == null) {
return false;
}
ListNode slow = head;
ListNode fast = head.next;
while (true) {
if (fast.next == null || fast.next.next == null) {
return false;
}
if (slow == fast) {
return true;
}
fast = fast.next.next;
slow = slow.next;
}
}
}
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
"""
if head is None or head.next is None:
return False
slow, fast = head, head.next
while True:
if fast.next is None or fast.next.next is None:
return False
if slow is fast:
return True
slow = slow.next
fast = fast.next.next
相关文章推荐
- Leetcode 141 Linked List Cycle
- 141. Linked List Cycle
- leetcode_141题——Linked List Cycle (set)
- 141. Linked List Cycle LeetCode
- LeetCode - 141/142 - Linked List Cycle
- 141-Linked List Cycle
- Leetcode#141(链表)-Linked List Cycle
- 141. Linked List Cycle
- [Leetcode 141] Linked List Cycle
- 141. Linked List Cycle
- LeetCode 141 -Linked List Cycle ( JAVA )
- LeetCode: Linked List Cycle [141]
- leetCode #141 Linked List Cycle
- [leetcode 141] Linked List Cycle----判断链表是否为循环链表
- leetcode-141-Linked List Cycle
- 141. Linked List Cycle
- LeetCode141:Given a linked list, determine if it has a cycle in it.
- leetcode_141_Linked List Cycle
- 141、142 Linked List Cycle & II
- [leetcode]141 Linked List Cycle