[leetcode]141. Linked List Cycle

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

Follow up:
Can you solve it without using extra space?

分析:

判断一个链表是否为环形链表,且不要使用额外空间。判断环形链表通常利用快慢指针来做,快指针一次走两步,慢指针一次走一步,若存在环,则快指针定会与慢指针相遇,

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

猜你喜欢

转载自blog.csdn.net/weixin_41814716/article/details/84333422