现在的位置: 首页 > 综合 > 正文

LeetCode | Linked List Cycle(判断链表是否有环)

2018年04月09日 ⁄ 综合 ⁄ 共 370字 ⁄ 字号 评论关闭

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

Follow up:

Can you solve it without using extra space?

题目解析:

判断是否有环,只需要快慢指针即可。注意考虑程序的健壮性。

class Solution {
public:
    bool hasCycle(ListNode *head) {
        if(head == NULL || head->next == NULL)
            return false;
        ListNode *p,*q;
        p = head;
        q = head->next;
        while(q->next && p!=q){
            p = p->next;
            if(q->next->next == NULL )
                return false;
            q = q->next->next;
        }
        if(p == q)
            return true;
        else
            return false;
    }
};

抱歉!评论已关闭.