您的位置:首页 > 其它

LeetCode 141 Linked List Cycle(链表判环)

2017-04-18 21:14 483 查看
Given a linked list, determine if it has a cycle in it.

Follow up:

Can you solve it without using extra space?

题目大意:不使用额外空间的情况下,判断链表中有没有环。

解题思路:“快慢指针”,使用两个指针slow和fast,slow每次向后移动一步,fast每次向后移动两步,如果两个指针相遇,说明链表中存在环,反之则无环。

代码如下:

/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
bool hasCycle(struct ListNode *head) {
struct ListNode* slow = head;
struct ListNode* fast = head;
if(!head) return false;
while(slow && fast && fast->next){
slow = slow->next;
fast = fast->next->next;

if(fast == slow) return true;
}
return false;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  LeetCode