141. Linked List Cycle

来源:互联网 发布:音乐剪辑软件手机 编辑:程序博客网 时间:2024/05/21 03:24

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

solution :

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

心得:快慢指针法,要想到这个就比较简单。

运行速度:快


0 0