您的位置:首页 > 其它

[LeetCode-141] Linked List Cycle(判断链表是否有环)

2015-10-08 22:33 471 查看
Given a linked list, determine if it has a cycle in it.

Follow up:

Can you solve it without using extra space?

【分析】

由于每一个父亲只有可能有一个孩子,故这里的环实际上是指list中某一个节点的孩子同时也是它自己或者他的祖先。 这个问题需要注意几种情况:

1. 空链表不成环

2. 一个节点自环

3. 一条链表完整成环

不能开额外的空间,即空间复杂度是o(1)。该问题是经典面试问题,其标准解法是用两个指针,一快一慢,如果在快的指针能够追上慢的指针,则有环,否则无环。

代码如下:

/**
* Definition for singly-linked list.
**/
struct ListNode {
int val;
struct ListNode *next;
};

bool hasCycle(struct ListNode *head) {
if(!head)
return false;
struct ListNode *fast = head;
struct ListNode *slow = head;

while(fast!=NULL&&fast->next!=NULL) {

fast = fast->next->next;
slow = slow->next;
if(fast==slow)
return true;
}

return false;
}

改进版的代码

/*Improved version of the program*/
bool hasCycle(struct ListNode *head) {
if(!head)
return false;
struct ListNode *fast = head;
struct ListNode *slow = head;

do {
if(!fast||!slow)
return false;/*If LinkNode exist NULL node,then return false*/
fast = fast->next;
slow = slow->next;
if(fast)
fast = fast->next;
else
return false;/*If LinkNode exist NULL node,then return false*/
}while(fast!=slow);

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