#include <stdbool.h> /**

  • struct ListNode {
  • int val;
  • struct ListNode *next;
  • };
  • C语言声明定义全局变量请加上static,防止重复定义 */

/** *

  • @param head ListNode类
  • @return bool布尔型 / / bool hasCycle(struct ListNode* head ) { // write code here if(head==NULL||head->next==NULL){ return false; } struct ListNode *p1=head->next; while(p1->next!=head->next){ if(p1->next==NULL){ return false; } p1=p1->next; } return true; //我的本意是直接去用一个指针去遍历,如果有循环圈圈的话,一定会p1->next==第二个节点的地址,但是这个方法好像超时了 } / //这里我用参考大神的方法去写,这里我使用快慢指针的方法,慢指针每次都执行一次next,而快指针每次都执行两次的next,如果有循环的话,两个地址一定会遇见 bool hasCycle(struct ListNode head ) { if(head==NULL||head->next==NULL){ return false; } struct ListNode *slow = head, *fast = head; while (fast && fast->next) { slow = slow->next; fast = fast->next->next; if (slow == fast) return true; } return false;

}