[LeetCode] Linked List Cycle
生活随笔
收集整理的這篇文章主要介紹了
[LeetCode] Linked List Cycle
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
解題思路
使用快慢兩個指針,如果快的指針趕上了慢的,則說明存在回路。
實現(xiàn)代碼
/*** Definition for singly-linked list.* struct ListNode {* int val;* ListNode *next;* ListNode(int x) : val(x), next(NULL) {}* };*///Runtime:18 ms class Solution { public:bool hasCycle(ListNode *head) {if (head == NULL){return false;}ListNode *slow = head;ListNode *fast = head;while (fast->next && fast->next->next){slow = slow->next;fast = fast->next->next;if (fast == slow){return true;}}return false;} };總結(jié)
以上是生活随笔為你收集整理的[LeetCode] Linked List Cycle的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: *CI框架装载器Loader.php源码
- 下一篇: 团队在Github上协同开发项目流程