leetcode之Linked List Cycle II

问题描述如下:

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

Follow up:
Can you solve it without using extra space?

问题链接

cpp代码如下:

class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        if(head==NULL)return NULL;
        ListNode* f=head,*s=head;
        do{
            f=f->next;
            if(!f)return NULL;
            f=f->next;
            if(!f)return NULL;
            s=s->next;
        }while(f!=s);
        f=head;
        while(f!=s){
            f=f->next;
            s=s->next;
        }
        return f;
    }
};


猜你喜欢

转载自blog.csdn.net/wocaoqwerty/article/details/41773849
今日推荐