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?

分析

判斷一個鏈表中是否有循環。一種方法是將鏈表指針依次保存在數組中,看下一個節點是否會在數組中出現,另一種方法是用兩個指針,一個前進一步,另一個前進兩步,如果存在循環,兩個指針肯定有重合的時候。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
bool hasCycle(struct ListNode *head) {
    struct ListNode *array[100000];
    int num=0;
    struct ListNode *p=head;
    while(p!=NULL)
    {
        for(int i=0;i<num;i++)
        {
            if(p==array[i])
                return true;
        }
        array[num]=p;
        num++;
        p=p->next;
    }
    return false;
}
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
bool hasCycle(struct ListNode *head) {
    if(head==NULL)
        return false;
    struct ListNode *p1=head,*p2=head->next;
    while(p1!=NULL&&p2!=NULL)
    {
        if(p1==p2)
            return true;
        p1=p1->next;
        if(p2->next!=NULL)
            p2=p2->next->next;
        else
            p2=p2->next;
    }
    return false;
}
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容