四种语言刷算法之环形链表

力扣141. 环形链表

1、C

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
bool hasCycle(struct ListNode *head) {
    if(head==NULL||head->next==NULL)return false;
    struct ListNode* p = head->next;
    struct ListNode* q = p->next;
    while(p!=NULL && q!=NULL){
        if(p==q)return true;
        else{
            p = p->next;
            if(q->next==NULL)return false;
            else{
                q = q->next->next;
            }
        }
    }
    return false;
}

2、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 *p = head;
        ListNode *q = head;
        while(p!=NULL&&q!=NULL){
            p = p->next;
            if(q->next!=NULL){
                q = q->next->next;
            }
            else{
                return false;
            }
            if(p==q){return true;}
        }
        return false;
    }
};

3、JAVA

/**
 * 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 *p = head;
        ListNode *q = head;
        while(p!=NULL&&q!=NULL){
            p = p->next;
            if(q->next!=NULL){
                q = q->next->next;
            }
            else{
                return false;
            }
            if(p==q){return true;}
        }
        return false;
    }
};

4、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
        """
        p = head
        q = head
        while(p is not None and q is not None):
            p = p.next
            if(q.next is not None):
                q = q.next.next
            else:
                return False
            if(p==q):
                return True
        return False
posted @ 2023-04-17 10:31  菜鸟冲冲冲  阅读(35)  评论(0)    收藏  举报