LeetCode OJ 141. Linked List Cycle
Description
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
解题思路
对于判断环的问题,可以采用双指针(快慢指针)的方法来判断。另外,因为题目中给的ListNode结构体只有一个next指针,所以不存在中间有环的情况。
另外还有一种方法是指针q用于遍历链表节点,每次移动一个节点,并且记录当前所经过的节点数。指针p每次从表头开始遍历,直到与指针q相等。如果p和q走过的步数不同,则存在环。否则,当q走到了链表尾节点,每次p,q步数都相同,那么链表不存在环。但是这样的时间复杂度比较高O(n^2)。
代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool hasCycle(ListNode *head) {
if(head == NULL || head->next == NULL)
return false;
ListNode *p,*q;
p = q = head;
while(p && q){
p = p->next;
q = q->next;
if(q != NULL)
q = q->next;
if(p != NULL && p == q)
return true;
}
return false;
}
};