链表中与环相关的问题
来源:互联网 发布:淘宝没给发票 编辑:程序博客网 时间:2024/06/04 18:10
141. Linked List Cycle
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
Subscribe to see which companies asked this question
题目链接
利用一个快指针,一个慢指针。如果它们能相遇,则存在环。
/** * Language: cpp ( 9ms ) * 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) { if(head==NULL||head->next==NULL){ return false; } ListNode* fast=head,*slow=head->next; while(fast!=slow){ if(slow->next==NULL||slow->next->next==NULL){ return false; }else{ fast=fast->next; slow=slow->next->next; } } return true; }};
142. Linked List Cycle II
Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
Note: Do not modify the linked list.
Follow up:
Can you solve it without using extra space?
题目链接
判断环的入口点 :相遇点到环入口的距离等于头节点到环入口的距离。
class Solution {public: ListNode *detectCycle(ListNode *head) { if(head==NULL||head->next==NULL){ return NULL; } ListNode *slow=head,*fast=head; while(fast!=NULL&&fast->next!=NULL){ fast=fast->next->next; slow=slow->next; if(fast==slow){ break; } } if(fast!=slow){ return NULL; } slow=head; while(fast!=slow){ fast=fast->next; slow=slow->next; } return fast; }};
计算环的长度
如何判断两个链表(不带环)是否相交
资料参考
0 0
- 链表中与环相关的问题
- 单链表 与 环 的相关问题
- 与中断相关的问题
- 与中断相关的问题
- 与编译器相关的问题
- 与阶乘相关的问题
- 与中断相关的问题
- 环的相关问题
- 与OSGi的相关的问题
- 与SQL Server补丁相关的问题
- 与SQL Server补丁相关的问题
- 与SQL Server补丁相关的问题
- 与SQL Server补丁相关的问题
- 与SQL Server补丁相关的问题
- 与SQL Server补丁相关的问题
- 与SQL Server补丁相关的问题
- 与SQL Server补丁相关的问题
- 与SQL Server补丁相关的问题
- java I/O流FileInputStream和FileReader使用及乱码问题
- 使用Markdown编辑器写博客
- Docker-Windows 2008 R2安装使用
- Nand Flash基础知识与坏块管理机制的研究
- js学习笔记:引用类型——Array
- 链表中与环相关的问题
- Angular的$broadcast,$emit and $on
- isEmpty和isBlank区别
- js简单学-主计时器
- Android ListView的OnItemClickListener()参数详解
- [电影]《指环王》新老三部曲完全赏析(魔戒再现)
- ajax VS websocket
- ibatis 中like使用
- 查找二叉树的最小深度