但有點奇怪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;
}
20240807 更新
為了複習重寫了,果然已經忘記為什麼它可以這樣跑了XD(大笑)
但現在的寫法已經有系統多了,可喜可賀。
struct ListNode *detectCycle(struct ListNode *head) {
struct ListNode *pfast , *pslow;
pfast = head;
pslow = head;
while (pfast != NULL && pfast->next != NULL)
{
pslow = pslow->next;
pfast = pfast->next;
pfast = pfast->next;
if (pslow == pfast)
{
pfast = head;
while (pslow != pfast)
{
pslow = pslow->next;
pfast = pfast->next;
}
return pslow;
}
}
return NULL;
}
沒有留言:
張貼留言