【2024考研】题解5 | #判断链表中是否有环#
判断链表中是否有环
https://www.nowcoder.com/practice/650474f313294468a4ded3ce0f7898b9
/** * 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) { //write code here //1.特例表空 if(head == NULL) return false; //2.定义快慢两个指针 ListNode *fast = head; ListNode *slow = head; //没有环的情况下快指针肯定先到到表尾 while(fast != NULL && fast->next != NULL){ fast = fast->next->next; slow = slow->next; //快慢指针相遇即肯定有环 if(slow == fast) return true; } return false; } };
2024考研数据结构 文章被收录于专栏
本人考研刷算法题,立此专栏练习强化。