LeetCode 141. Linked List Cycle

    xiaoxiao2021-03-25  93

    题目: 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 != NULL && fast->next != NULL){//用快慢指针方法,如果有循环 fast = fast->next->next; if(fast == slow){//则一定存在相遇情况 return true; } } return false; } };
    转载请注明原文地址: https://ju.6miu.com/read-10380.html

    最新回复(0)