leetcode 141

141. Linked List Cycle

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

Follow up:
Can you solve it without using extra space?

判断一个单链表中是否存在环。不利用额外的空间。

思路:初始两个指针都指向头结点,一个指针每次移动一次,另一个指针每次移动两次,若移动多的指针再次与移动慢的指针相等的话,则该链表存在环。

代码如下:

 

 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         ListNode * slow = head;
13         ListNode * fast = head;
14         while(fast != NULL && fast->next != NULL )
15         {
16             fast = fast->next->next;
17             slow = slow->next;
18             if(fast == slow)
19             {
20                 return true;
21             }
22         }
23         return false;
24     }
25 };

 

posted @ 2016-10-10 21:22  花椰菜菜菜菜  阅读(95)  评论(0编辑  收藏  举报