코테준비 - Linked List Cycle II

정상화·2023년 2월 26일

LeetCode

목록 보기
138/222

Linked List Cycle II

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        auto v = head, w = head;

        if (head == nullptr || head->next == nullptr) {
            return nullptr;
        }
        do {
            v = v->next;
            w = w->next->next;
        } while (w != nullptr && w->next != nullptr && v != w);

        if (w == nullptr || w->next == nullptr) {
            return nullptr;
        }

        w = head;
        while (v != w) {
            v = v->next;
            w = w->next;
        }

        return v;
    }
};
profile
백엔드 희망

0개의 댓글