141. Linked List Cycle (链表)

来源:互联网 发布:剑灵帅气灵男捏脸数据 编辑:程序博客网 时间:2024/06/06 18:14

https://leetcode.com/problems/linked-list-cycle/description/

题目:判断链表是否存在环。

思路:用2个指针,慢指针每次加一,快指针每次加二,如果有一个指针为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) {        ListNode *l=head;        ListNode *r=head;        while(1)        {            if(r==NULL||r->next==NULL) return 0;            l=l->next;            r=r->next->next;            if(l==r) return 1;        }    }};
原创粉丝点击