leetcode 10: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 bool hasCycle(ListNode *head) { 2 if(head == NULL) 3 return false; 4 ListNode* slow = head; 5 ListNode* fast = head; 6 while(fast->next != NULL && fast->next->next != NULL){ 7 slow = slow->next; 8 fast = fast->next->next; 9 if(fast == slow) 10 return true; 11 } 12 return false; 13 }