带环链表-LintCode
2017-07-12 10:13
246 查看
给定一个链表,判断它是否有环。
思想:
设置两个指针(fast, slow),初始值都指向头,slow每次前进一步,fast每次前进二步,如果链表存在环,则fast必定先进入环,而slow后进入环,两个指针必定相遇。
思想:
设置两个指针(fast, slow),初始值都指向头,slow每次前进一步,fast每次前进二步,如果链表存在环,则fast必定先进入环,而slow后进入环,两个指针必定相遇。
#ifndef C102_H #define C102_H #include<iostream> using namespace std; class ListNode{ public: int val; ListNode *next; ListNode(int val){ this->val = val; this->next = NULL; } }; class Solution { public: /** * @param head: The first node of linked list. * @return: True if it has a cycle, or false */ bool hasCycle(ListNode *head) { // write your code here ListNode *fast = head, *slow = head; while (fast&&fast->next) { slow = slow->next; fast = fast->next->next; if (slow == fast) { return true; break; } } return false; } }; #endif
相关文章推荐
- *[Lintcode]带环链表 II
- 【LintCode】 Linked List Cycle 带环链表
- lintcode(102)带环链表
- [LintCode 102] 带环链表(Python)
- LintCode 带环链表(快慢指针法)
- LintCode-带环链表 II
- [LintCode] 带环链表 II Linked List Cycle II
- lintcode--带环链表II
- lintcode 带环链表(102)
- lintcode-带环链表-102
- LintCode(103)带环链表 II
- LintCode_103_带环链表 II
- lintcode-102-带环链表
- lintcode(103)带环链表 II
- lintcode-103-带环链表 II
- LintCode 带环链表
- 判断两个链表是否相交,若相交,求交点,考虑带环情况实现代码
- 判断链表是否带环
- LintCode 删除链表中等于给定值val的所有节点
- LintCode 链表倒数第n个节点