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?

注意,链表循环并不是尾指针和头指针相同,可能是在中间某一段形成一个环路,所以不能只判断元素和第一个元素是否存在重合

先设置两个指针p_fast和p_slow。从头开始遍历链表,p_fast每次走两个节点,而p_slow每次走一个节点,若存在循环,这两个指针必定重合:

 /**
* 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) return false; ListNode *p_fast = head;
ListNode *p_slow = head; do{
p_slow = p_slow->next;
if(p_fast != NULL)
p_fast = p_fast->next;
if(p_fast != NULL)
p_fast = p_fast->next;
else
return false;
}while(p_fast != p_slow); return true; }
};
上一篇:1级搭建类104-Oracle 12cR2 单实例 FS(阿里云)公开


下一篇:pushlet实现服务器端向客户端推送信息