LeetCode--Linked List Cycle
2014-05-14 22:17
141 查看
Linked List Cycle
Total Accepted: 17148 TotalSubmissions: 49300My Submissions
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; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: bool hasCycle(ListNode *head) { /* 1. 空链表不成环 2. 一个节点自环 3. 一条链表完整成环 */ if(head==NULL)return false; if(head->next==NULL)return false; if(head->next==head)return true; ListNode* y=head->next; ListNode* x=head->next->next; while(x!=NULL && y!=NULL) { x=x->next; if(x==NULL)break; x=x->next; y=y->next; if(x==y)break; } return x==y; } };标准做法是使用两个指针,一个每次往前走2步,一个每次往前走1步,如果两个指针相遇,即说明链表有环,时间复杂度为O(N),空间复杂度为O(1)。
相关文章推荐
- leetcode 141 Linked List Cycle C++
- LeetCode: Linked List Cycle 解题报告
- [LeetCode] Linked List Cycle, Solution
- [LeetCode] Linked List Cycle II
- [Leetcode 141 & 142, medium] Linked List Cycle (I and II)
- Leetcode Linked List Cycle
- leetCode-linkedListCycle判断链表是否有环
- leetcode linked-list-cycle(i 、ii)(java实现)
- LeetCode--linked-list-cycle-ii
- LeetCode | Linked List Cycle
- leetcode - Linked List Cycle II
- LeetCode: Linked List Cycle
- LeetCode题解——Linked List Cycle
- [LeetCode]Linked List Cycle
- [LeetCode]Linked List Cycle
- [Leetcode]Linked List Cycle
- LeetCode | Linked List Cycle(判断链表是否有环)
- leetcode:142. Linked List Cycle II(Java)解答
- 【LeetCode】Linked List Cycle II
- leetcode_141_Linked List Cycle