Leetcode Linked List Cycle

来源:互联网 发布:js修改sass变量 编辑:程序博客网 时间:2024/06/06 02:19

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

使用两个指针,一前一后,(p,q),p与q相差一个位置,之后p移动一步,q相对应移动两步,如果存在环,那么q和p一定会相遇

/** * 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,*q;        if(head==NULL)         {            return false;        }        p = head;        q = head->next;         while(q!=NULL && q->next!=NULL)         {             if(p==q)              {                 return true;             }             p = p->next;             q = q->next;             q = q->next;         }         return false;    }};


0 0
原创粉丝点击