Skip to content

Latest commit

 

History

History
86 lines (64 loc) · 1.86 KB

_141. Linked List Cycle.md

File metadata and controls

86 lines (64 loc) · 1.86 KB

All prompts are owned by LeetCode. To view the prompt, click the title link above.

Back to top


First completed : June 03, 2024

Last updated : July 01, 2024


Related Topics : Hash Table, Linked List, Two Pointers

Acceptance Rate : 50.586 %


Solutions

Python

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

class Solution:
    def hasCycle(self, head: Optional[ListNode]) -> bool:
        visited = set()

        if not head :
            return False

        currNode = head
        while currNode.next :
            visited.add(currNode)
            currNode = currNode.next
            if currNode in visited :
                return True

        return False

C

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
bool hasCycle(struct ListNode *head) {
    // Since no dynamic space and I don't feel like implementing a full datastructure,
    // let's do a 2-pointer method

    if (!head || !head->next) {
        return false;
    }

    struct ListNode *one = head;
    struct ListNode *two = head->next;

    while (one != two) {
        if (!two->next || !two->next->next) {
            return false;
        }
        one = one->next;
        two = two->next->next;
    }

    return true;
    
}