leetcode || 141、Linked List Cycle

来源:互联网 发布:人防指挥所智能化软件 编辑:程序博客网 时间:2024/05/16 10:32

problem:

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

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

Hide Tags
 Linked List Two Pointers

thinking:

(1)如果可以开设额外的空间,使用unordered_set存储遍历过的结点,出现重复时即为存在环形结构

(2)如果不适用额外的空间,及空间复杂度为O(1),这里使用快、慢双指针。慢指针每次走一步,快指针每次走两步。

如果存在环形结构,两个指针总会相遇。

(3)终止条件也要注意:

fast!=NULL && fast->next!=NULL

防止出现fast->NULL->next

code:

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    bool hasCycle(ListNode *head) {          ListNode *fast,*slow;         if(head==NULL) return false;         slow=head;         fast=head->next;         while(fast!=NULL && fast->next!=NULL)         {             if(slow==fast) return true;             slow=slow->next;             fast=fast->next->next;         }         return false;    }};


0 0
原创粉丝点击