leetcode——142——Linked List Cycle II
2016-05-02 21:57
447 查看
Given a linked list, return the node where the cycle begins. If there is no cycle, return
Note: Do not modify the linked list.
Follow up:
Can you solve it without using extra space?
null.
Note: Do not modify the linked list.
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: int numNode = 0; ListNode *detectCycle(ListNode *head) { if (!hasCycle(head)) return NULL; ListNode* pBegin = head; ListNode* pEnd = head; for (int i = 0; i < numNode; i++) pBegin = pBegin->next; while (pBegin != pEnd) { pBegin = pBegin->next; pEnd = pEnd->next; } return pBegin; } bool hasCycle(ListNode *head) { if (head == NULL || head->next == NULL) return false; ListNode* fast = head; ListNode* slow = head; while (fast != NULL) { fast = fast->next; if (fast != NULL) { fast = fast->next; slow = slow->next; numNode++; } if (fast == slow) return true; } return false; } };
相关文章推荐
- 百练+BFS+图上visit标记嘛,因为是最短嘛,防止重复嘛
- 项目1-点-圆-圆柱类族的设计(3)
- Chrome和Firefox常用插件
- java中的IO整理
- 【DP】探索数字迷塔
- 什么是ajas
- HTTP系列(二):连接管理
- 安装并运行Elasticsearch
- Redis+Spring缓存实例(windows环境,附实例源码及详解)
- 六、树和二叉树--(0)什么是树
- ABP中动态WebAPI原理解析
- 【Unity】11.2 刚体(Rigidbody)
- 顺序表的基本操作
- leetcode 283---Move Zeroes&&对vector erase()和remove用法的感悟
- Error running app: Instant Run requires 'Tools | Android | Enable ADB integration' to be enable
- 一起talk C栗子吧(第一百四十五回:C语言实例--socket概述)
- 使用特定analyzer分析文本
- centos 下用shell脚本启动jar包
- laravel5.2 多表验证
- PyQt5教程——布局管理(4)