LeetCode OJ:Linked List Cycle
2014-01-19 22:10
330 查看
Linked List Cycle
Total Accepted: 7416 TotalSubmissions: 21273My Submissions
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
算法思想:一个指针速度1向后走,一个指针速度2向后走,若相遇则必有环,(有环则必相遇)。
/** * 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 *p=head,*q=head; while(q!=NULL&&q->next!=NULL){ p=p->next; q=q->next->next; if(p==q)return true; } return false; } };
相关文章推荐
- LeetCode OJ平台上Linked List Cycle题目用java快慢遍历实现
- 【LeetCode OJ】Linked List Cycle
- 【LeetCode OJ】Linked List Cycle II
- LeetCode OJ:Linked List Cycle II
- [LeetCode OJ] Linked List Cycle 解题报告
- [LeetCode OJ]Linked List Cycle
- 【LeetCode OJ】Linked List Cycle
- LeetCode OJ:Linked List Cycle II(循环链表II)
- LeetCode OJ-- Linked List Cycle II **
- 【LeetCode OJ】Linked List Cycle
- LeetCode OJ:Linked List Cycle(链表循环)
- LeetCode OJ - Linked List Cycle II
- LeetCode OJ - Linked List Cycle
- LeetCode OJ 之 Linked List Cycle (判断链表是否有环)
- LeetCode Linked List Cycle II(Floyd 判圈算法)
- [leedcode 141] Linked List Cycle
- Linked List Cycle
- leetCode:Linked List Cycle II
- LeetCode OJ - Flatten Binary Tree to Linked List
- Linked List Cycle II