环形链表

使用双指针技巧,判断链表中是否有环。

 

struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
public:
    bool hasCycle(ListNode *head) {
        if(head == NULL)
            return false;
        ListNode *s = head;
        ListNode *f = head;
        while(f->next != NULL){
            f = f->next;
            if(f->next == NULL){
                return false;
            }
            else{
                f = f->next;
                s = s->next;
                if(f == s){
                    return true;
                }
            }
        }
        return false;
    }
};

 

posted @ 2020-03-10 22:36  jenningszheng  阅读(165)  评论(0编辑  收藏  举报