LeetCode 141. Linked List Cycle

来源:互联网 发布:2014大学生就业率数据 编辑:程序博客网 时间:2024/06/03 22:39

Linked List Cycle


题目思路:

判断给定的链表中是否存在环。

参考这篇文章


题目代码:

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

原创粉丝点击