您的位置:首页 > 其它

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: