leetcode 141. Linked List Cycle

来源:互联网 发布:大数据专业课程有哪些 编辑:程序博客网 时间:2024/06/13 22:29

Given a linked list, determine if it has a cycle in it.
/**
* 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) return false;        while(head->next){            if(!head->next->next)            {                break;            }          if(head->next==head->next->next)          {              return true;          }            head->next=head->next->next;            head=head->next;        }        return false;    }};

一个指针每次走一步,一个指针走两步,有环的时候会相遇。

0 0
原创粉丝点击