Linked List Cycle【leetcode】

来源:互联网 发布:javascript 数组clear 编辑:程序博客网 时间:2024/06/16 18:45


判断链表是否有环,笔试题做过很多次了。

定义一个快指针,一个慢指针,若有环,则他们最后一定会相遇。


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


0 0
原创粉丝点击