给定一个链表,判断链表中是否有环。

进阶:
你能否不使用额外空间解决此题?


/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
bool hasCycle(struct ListNode *head) {
    struct ListNode *pfast,*pslow;
    if(NULL == head || head->next == NULL)
    {
        return false;
    }
    pfast = pslow = head;
    while(pfast->next != NULL && pfast->next->next !=NULL)
    {
        pfast = pfast->next->next;
        pslow = pslow->next;
        if(pfast == pslow)
        {
            return true;
        }
    }
    return false;
}

 


内容来源于网络如有侵权请私信删除
你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!

相关课程