带环链表
给定一个链表,判断它是否有环。
解题
定义两个指针p1 p2
p1每次向前走一步
p2每次向前走两步
当p2能赶上p1的时候说明有环
/**
* Definition for ListNode.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int val) {
* this.val = val;
* this.next = null;
* }
* }
*/
public class Solution {
/**
* @param head: The first node of linked list.
* @return: True if it has a cycle, or false
*/
public boolean hasCycle(ListNode head) {
// write your code here
if(head == null || head.next == null)
return false;
ListNode p1 = head;
ListNode p2 = head;
p2 = p2.next;
while(p2.next!=null && p2.next.next!=null){
if(p1 == p2){
return true;
}
p1 = p1.next;
p2 = p2.next.next;
}
return false;
}
}
Java Code
"""
Definition of ListNode
class ListNode(object): def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param head: The first node of the linked list.
@return: True if it has a cycle, or false
"""
def hasCycle(self, head):
# write your code here
if head == None or head.next == None:
return False
slow = head
fast = head
fast = fast.next
while fast.next!=None and fast.next.next!=None:
if fast == slow:
return True
else:
slow = slow.next
fast = fast.next.next
return False
Python Code