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?

設兩個指向輸入鏈表的指針,walker和runner,製造一個while函數,一次循環walker指向下一個鏈表,runner指向下下個鏈表,如果輸入鏈表是一個環,那麼walker和runner總有相遇的一次,如果它們指向同一個鏈表中的元素,那麼返還true,如果鏈表有結束的節點,則返還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 *walker=head;
           struct ListNode *runner=head;
           while(head->next!=NULL && head->next->next!=NULL){
               walker=head->next;
               runner=head->next->next->next;
               if(walker==runner)
               return true;
           }
           return false;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章