Leetcode--Linked List Cycle

来源:互联网 发布:刘文典打蒋介石知乎 编辑:程序博客网 时间:2024/06/03 17:29

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

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


下面是错误的解法:

声明两个指针cur nex ,一个(cur)指向头指针,另一个(nex)遍历直到cur==nex 或 nex==NULL

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

Submission Result: Time Limit Exceeded

这个错误用这个图可以解释:


程序执行这种情况就是个死循环

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==NULL||head->next==NULL)            return false;        ListNode *fast=head;        ListNode *slow=head;        while(fast!=NULL&&fast->next!=NULL)//fast->nex有意义的前提是fast不为NULL        {            slow=slow->next;            fast=fast->next->next;            if(slow==fast)                return true;        }        return false;    }};




0 0
原创粉丝点击