BM6 判断链表中是否有环
每天刷刷面试题目,新的感悟就通过写博客发出来了,就不需要用一些云笔记去整理了哈哈,希望大佬们不要介意~
今天的题目比较简单,但是对运行时间有点要求:
#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;
}