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;
}

  

posted @ 2017-03-12 11:11  世人谓我恋长安  阅读(129)  评论(0编辑  收藏  举报