leetcode--Linked List Cycle

来源:互联网 发布:淘宝市场行情租用 编辑:程序博客网 时间:2024/06/18 15:23

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

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

不开辟新空间,就不能开辟rear指针,另循思路

/** * 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 *p,*s;        if (head==NULL||head->next==NULL)        return false;        p=head;        s=head;            while(s->next->next!=NULL)//判断最后面的情况就行            {                p=p->next;                s=s->next->next;                if(p==s)                return true;                //遗漏掉的情况,导致错误,               //如果s->next指向NULL,而s->next->next可能指向头结点            if(s->next==NULL)                   return false;            }            return false;    }};
0 0