Easy 141题 Linked List Cycle Medium 142题 Linked List Cycle II
来源:互联网 发布:linux test -e 编辑:程序博客网 时间:2024/05/23 00:08
Question:
Given a linked list, determine if it has a cycle in it.
Solution:
/** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */public class Solution { public boolean hasCycle(ListNode head) { if(head==null) return false; ListNode slow=head; ListNode fast=head; while(fast.next!=null&&fast.next.next!=null){ slow=slow.next; fast=fast.next.next; if(slow==fast) return true; } return false; }}
Question:
Given a linked list, return the node where the cycle begins. If there is no cycle, returnnull
.
Note: Do not modify the linked list.
Solution:
/** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */public class Solution { public ListNode detectCycle(ListNode head) { if(head==null) return null; ListNode slow=head; ListNode fast=head; ListNode tmp=null; while(fast.next!=null&&fast.next.next!=null){ slow=slow.next; fast=fast.next.next; if(slow==fast){ tmp=slow; break; } } if(tmp==null) return null; //show and fast are the same slow=tmp; fast=head; while(slow!=fast){ slow=slow.next; fast=fast.next; } return slow; }}
0 0
- Easy 141题 Linked List Cycle Medium 142题 Linked List Cycle II
- LeetCode.142(141) Linked List Cycle && Linked List Cycle (II)
- [Leetcode 141 & 142, medium] Linked List Cycle (I and II)
- Linked List Cycle II Linked List Cycle
- 142Linked List Cycle II
- 142Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Medium 333题 Largest BST Subtree
- Shell脚本基础知识及案例
- 静态与动态链接库
- matlab cell to str
- one method to resolve table cell can not be selected
- Easy 141题 Linked List Cycle Medium 142题 Linked List Cycle II
- 使用YOLO训练自己的数据样本经验总结
- 重要的不是解决,而是寻找
- atom使用快捷键
- [.NET] 打造一个很简单的文档转换器 - 使用组件 Spire.Office
- 天天团购 切底去除版权、删除版权
- C++11用两个线程轮流打印整数
- Memcached远程代码执行漏洞预警与检测修复
- Leetcode题解:11. Container With Most Water