LeetCode-141:Linked List Cycle
来源:互联网 发布:手机淘宝咋退货退款 编辑:程序博客网 时间:2024/06/07 15:15
原题描述如下:
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
题意
:给定一个链表,判断该链表中是否出现了环。
解题思路:
设定两个指针分别指向头结点,每次让第一个指针走一步,第二个指针走两步,若最终两个指针再次相遇,则说明存在环。
Java代码:
/*** 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 first = head;
ListNode second = head;
while(second != null && second.next != null){
first = first.next;
second = second.next.next;
if(first == second){
return true;
}
}
return false;
}
}
0 0
- LeetCode(141)Linked List Cycle
- LeetCode 141 Linked List Cycle
- LeetCode 141 Linked List Cycle
- LeetCode: Linked List Cycle [141]
- [leetcode 141] Linked List Cycle
- [leetcode]141 Linked List Cycle
- LeetCode 141 Linked List Cycle
- leetcode || 141、Linked List Cycle
- Leetcode[141]-Linked List Cycle
- leetcode-141-Linked List Cycle
- [Leetcode 141] Linked List Cycle
- leetcode 141: Linked List Cycle
- [Leetcode]#141 Linked List Cycle
- leetCode #141 Linked List Cycle
- leetcode: (141) Linked List Cycle
- [leetcode] #141 Linked List Cycle
- 【leetcode】【141】Linked List Cycle
- 【LEETCODE】141-Linked List Cycle
- HDU 5744 Keep On Movin(水题)
- TextView设置超链接、背景颜色、字体颜色等等,Spannable的使用。
- css 框模型要点
- caffe make runtest 错误
- iOS水波纹动画详解
- LeetCode-141:Linked List Cycle
- Android中View转换为Bitmap及getDrawingCache=null的解决方法
- 关于JAVA中的listener回调机制,以及其在Android中的使用
- XML配置文件
- ERROR 1146 (42S02): Table 'voucherdb.fvr_vouchersummary' doesn't exist
- DB2数据库的学习及总结
- kth largest element in an array
- 反射生成对象 获得方法及构造器
- java中HashMap的用法