141. Linked List Cycle

来源:互联网 发布:android仿淘宝首页 编辑:程序博客网 时间:2024/05/16 04:54

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

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

Subscribe to see which companies asked this question

注意加一个runner->next!=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 ||head->next->next==NULL) return false;        ListNode* walker=head->next;        ListNode* runner=head->next->next;        while(walker!=NULL && runner!=NULL&& runner->next!=NULL)        {            if(walker==runner) return true;            walker=walker->next;            runner=runner->next->next;        }        return false;    }};


0 0
原创粉丝点击