2018年2月23日 星期五

[142] Linked List Cycle II

於是第二塊蛋糕來了
但有點奇怪QQ
原本是用val來比的
但是會錯 O.o
只好改成pointer比
但是為什麼呢?(沉思)

Linked List Cycle II
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode *detectCycle(struct ListNode *head) {
    if (head == NULL || head->next == NULL)
        return NULL;

    struct ListNode *one, *two;
    one = two = head;
    while (one->next != NULL && two->next != NULL)
    {
        one = one -> next;
        two = two->next;
        if (two->next == NULL)
            return NULL;
        two = two->next;
        if (one == two)
        {
            two = head;
            while (one!=two)
            {
                one = one->next;
                two = two->next;
            }
            return one;
        }  
    }
    return NULL;

}

沒有留言:

張貼留言