题目链接:https://leetcode.cn/problems/linked-list-cycle/
一开始被题目里的pos误导了,后面直接看了官方题解,让我做感觉不一定做得出来,第一种方法估计会想不到增加一个set或者map或者vector保存链表节点的地址,第二种方法更想不到。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
/** * 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) { unordered_set<ListNode*> set; while (head) { if (set.count(head)) { return true; } set.insert(head); head = head->next; } return false; } */ bool hasCycle(ListNode *head) { if (!head || !head->next) { return false; } ListNode* slow = head; ListNode* fast = head->next; while (fast && fast->next) { if (slow == fast) { return true; } slow = slow->next; fast = fast->next->next; } return false; } }; |