Linked List Cycle

题目:

Given a linked list, determine if it has a cycle in it.

接口:

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

        return false;
    }
};

分析:

这道题目逻辑很直观,使用快慢指针,slow前进一步,fast前进两步。需要注意三点

(1) 检查head == NULL和head->next == NULL,这两个条件也为初始化做准备

(2) 初始化的时候slow = head, fast = head->next,这样能快速查知 head->next = head的情况

(3) while的退出条件是fast->next == NULL || fast->next->next == NULL

定义结点:

class ListNode{
public:
  int val;
  ListNode* next;
  ListNode(int x) : val(x), 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
        if (head == NULL || head->next == NULL) {
            return false;
        }

        ListNode* slow = head;
        ListNode* fast = head->next;

        while (fast->next != NULL && fast->next->next != NULL) {
            if (slow == fast) {
                return true;
            }
            slow = slow->next;
            fast = fast->next->next;
        }
        return false;
    }
};

results matching ""

    No results matching ""