码迷,mamicode.com
首页 > 其他好文 > 详细

[Algorithm] 11. Linked List Cycle

时间:2019-01-23 11:39:21      阅读:167      评论:0      收藏:0      [点我收藏+]

标签:red   osi   code   exp   which   bool   render   ||   class   

Description

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

To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.

Example

Example 1:

Input: head = [3,2,0,-4], pos = 1
Output: true
Explanation: There is a cycle in the linked list, where tail connects to the second node.

技术分享图片

Example 2:

Input: head = [1,2], pos = 0
Output: true
Explanation: There is a cycle in the linked list, where tail connects to the first node.

技术分享图片

Example 3:

Input: head = [1], pos = -1
Output: false
Explanation: There is no cycle in the linked list.

技术分享图片

Challenge

Follow up:
Can you solve it without using extra space? (O(1) (i.e. constant) memory)?

Solution

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     bool hasCycle(ListNode *head) {
12         if(head==NULL)  return false;
13         
14         ListNode *fast = head;
15         ListNode *slow = head;
16         
17         while(true){
18             // If a node is NULL, there is no cycle.
19             if(fast->next == NULL || fast->next->next == NULL)  return false;
20             
21             slow = slow->next;
22             fast = fast->next->next;
23             
24             // When the fast and the slow run into the same node, there‘s a cycle.
25             if ( slow->val == fast->val )
26                 return true;
27         }
28     }
29 };

 

[Algorithm] 11. Linked List Cycle

标签:red   osi   code   exp   which   bool   render   ||   class   

原文地址:https://www.cnblogs.com/jjlovezz/p/10307664.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!