大家好,我是蘇貝,本篇博客帶大家刷題,如果你覺得我寫的還不錯的話,可以給我一個贊👍嗎,感謝??
目錄
- 1.環形鏈表
- 解題
- 拓展:
- 2.環形鏈表II
1.環形鏈表
點擊查看題目
解題
思路:
bool hasCycle(struct ListNode *head) {struct ListNode *slow=head;struct ListNode *fast=head;while(fast&&fast->next){slow=slow->next;fast=fast->next->next;if(fast==slow)return true;}return false;
}
拓展:
1
慢指針一次走2步,快指針一次走3步,可以解決上面的題目嗎?
可以的,因為它們也只是相差了1步,證明同上
2
慢指針一次走1步,快指針一次走3步,走4步,…n步行嗎?下面用慢指針一次走1步,快指針一次走3步來證明
2.環形鏈表II
點擊查看題目
思路:
struct ListNode *detectCycle(struct ListNode *head) {struct ListNode *slow=head;struct ListNode *fast=head;while(fast&&fast->next){slow=slow->next;fast=fast->next->next;//1.找到相遇的節點if(slow==fast){//讓meet從相遇節點開始走struct ListNode *meet=slow;while(head!=meet){head=head->next;meet=meet->next;} return meet;}}return NULL;
}
好了,那么本篇博客就到此結束了,如果你覺得本篇博客對你有些幫助,可以給個大大的贊👍嗎,感謝看到這里,我們下篇博客見??