首页 > 代码库 > leetcode-141

leetcode-141

Linked List Cycle

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

Follow up:
Can you solve it without using extra space?

此题并不难,声明2个指针一个步长1,一个步长2,互相追逐,如果追上了就说明有循环,就是没有判断链表是否为空卡在那里很多时间。。。不说了。。。

附上c代码:

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

  

leetcode-141