[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)。该问题是经典面试问题,其标准解法是用两个指针,一快一慢,如果在快的指针能够追上慢的指针,则有环,否则无环。
代码如下:
改进版的代码
/*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;
}
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 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解
- LeetCode [Day 5] Longest Palindromic Substring 题解