Linked List Cycle解题报告

Description:

Given a linked list, determine if it has a cycle in it.

Example:

Given -21->10->4->5, tail connects to node index 1, return true

Link:

[http://www.lintcode.com/en/problem/linked-list-cycle/]

解题思路:

设定快慢指针,fast一次走两步,slow一次走一步,如果fast || fast->next == NULL则没有cycle,如果fast == slow 则存在循环。

Tips:

有两个指针,所以题目开始要查head和head->next是否为空。
在快慢指针跑起来以后,只要有循环那么一定会碰面,只要没有循环那么快指针肯定先到终点。

Time Complexity:

O(n)

完整代码:

bool hasCycle(ListNode *head) { if(head == NULL || head->next == NULL) return false; ListNode* fast; ListNode* slow; slow = head; fast = head->next; while(slow != fast) { if(fast == NULL || fast->next == NULL) return false; slow = slow->next; fast = fast->next->next; } return true; }

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容