1. 程式人生 > >判斷連結串列是否有環

判斷連結串列是否有環

/**
 * Definition of ListNode
 * class ListNode {
 * public:
 *     int val;
 *     ListNode *next;
 *     ListNode(int val) {
 *         this->val = val;
 *         this->next = NULL;
 *     }
 * }
 */
class Solution {
public:
    /**
     * @param head: The first node of linked list.
     * @return: True if it has a cycle, or false
     */
    bool hasCycle(ListNode *head) {
        // write your code here
        ListNode *onestep;
        ListNode *twosteps;
        if (!head)
            return false;
        onestep = head->next;
        if (head->next)
            twosteps = head->next->next;
        else
            return false;
        while (onestep && twosteps) {
            if (onestep == twosteps)
                return true;
            onestep = onestep->next;
            if (twosteps->next) {
                twosteps = twosteps->next->next;
            } else {
                return false;
            }
        }
        return false;
    }
};