LeetCode简单题:141. 环形链表(Python,C++,Java)

一.解法

https://leetcode-cn.com/problems/linked-list-cycle/
要点:双指针,hashmap/set
Python,C++,都用了相同的双指针法(快慢指针),如果是环形链表那么快指针必定追上慢指针
java用了hashset实现,如果发现当前节点已经存过,说明有环形出现

二.Python实现

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def hasCycle(self, head: ListNode) -> bool:
        fast=head
        slow=head
        while fast!=None:
            fast=fast.next
            if fast==None:
                 return False
            slow=slow.next
            fast=fast.next
            if fast==None:
                 return False
            if slow==fast:
                 return True
        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,*slow;
        fast=head;slow=head;
        if(!head) return false;
        while(fast){
            fast=fast->next;
            if(fast==NULL) return false;
            slow=slow->next;
            fast=fast->next;
            
            if(fast==slow) return true;
            
        }
        
        return false;
    }
};

四.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) {
    Set nodesSeen = new HashSet<>();
    while (head != null) {
        if (nodesSeen.contains(head)) {
            return true;
        } else {
            nodesSeen.add(head);
        }
        head = head.next;
    }
    return false;
}


}

你可能感兴趣的:(LeetCode简单题:141. 环形链表(Python,C++,Java))