LeetCode 141. Linked List Cycle

题意

判断一个单链表是否存在环

思路

设置两个指针快和慢,快指针每次前进两个节点,慢指针每次前进一个节点.

时间复杂度: O(n)

代码

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

你可能感兴趣的:(LeetCode,数据结构,leetcode,单链表,环)