141. Linked List Cycle


做题历程:

  1. 本题做了不止2次了,本次耗时2分钟独立解出

第一次做本题的时候还是很有挑战性的,但是,再以现在的眼光看,已经很简单了。就是运用快慢指针解答这道题,直接上代码:

/**
 * 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) {
        ListNode* slow = head;
        ListNode* fast = head;
        while (fast != nullptr && fast->next != nullptr) {
            slow = slow->next;
            fast = fast->next->next;
            if (slow == fast) {
                return true;
            }
        }
        return false;

    }
};

results matching ""

    No results matching ""