經過重覆數字的判斷以後(龜兔賽跑演算法), 就照做就好了
一塊蛋糕
只是我的蛋糕好像長的比別人的醜XD
為什麼又有多做很多判斷的感覺QQ
Linked List Cycle
/**
* 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 *one, *two;
one = two = head;
while (one->next != NULL && two->next != NULL)
{
one = one -> next;
two = two->next;
if (two->next == NULL)
return false;
two = two->next;
if (one->val == two->val)
return true;
}
return false;
}
然後又發現別人有偷吃步的方法!!!
這真是不可取 XD!
就是如果可以確定linked list裡面的值會是某些類別的話
(比方說一定是正數, 或是介於oo和 xx之間)
那就可以遍歷這個linked list (這個用語感覺不是我會用的詞XD)
每次將value 設成一個不在範圍內的值(比方說-1, 只要你的其它linked list不會有這個value即可),那麼繼續往下走, 如果走到一個node的value是你設的這個只有你知道的值(這個世界上只有三個人知道, 一個是linked list, 一個是我, 另一個我不能說!)(冷), 那麼就表示你回到一個你曾經走過的node了, cycle存在!!!
20230616 更新 為了練習linked list 又寫了一次
看起來沒什麼不一樣 XD 寫題目的果然是同一個我 XDDDDD
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
bool hasCycle(struct ListNode *head) {
struct ListNode *pSlow, *pFast;
pSlow= head;
pFast= head;
while (pSlow != NULL && pFast !=NULL)
{
pSlow=pSlow->next;
pFast=pFast->next;
if (pFast !=NULL)
pFast=pFast->next;
else
return false;
if (pSlow == pFast)
return true;
}
return false;
}
沒有留言:
張貼留言