LeetCode题解:Linked List Cycle
来源:互联网 发布:网络博客代理 编辑:程序博客网 时间:2024/06/11 22:43
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
题意:给定链表,判断是否为环。要求O(1)空间
思路:快慢指针,如果存在环,快指针必然遇到慢指针
代码:
/**
* 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 walker = head;
ListNode runner = head;
while(runner.next!=null && runner.next.next!=null) {
walker = walker.next;
runner = runner.next.next;
if(walker==runner) return true;
}
return false;
}
}
- LeetCode题解:Linked List Cycle
- [题解][LeetCode][Linked List Cycle]
- LeetCode题解:Linked List Cycle
- LeetCode题解:Linked List Cycle
- LeetCode Linked List Cycle & Linked List Cycle II题解
- [题解][LeetCode][Linked List Cycle II]
- LeetCode 题解(47): Linked List Cycle
- LeetCode题解——Linked List Cycle
- LeetCode题解:Linked List Cycle II
- Leetcode题解 141. Linked List Cycle
- Leetcode题解 141. Linked List Cycle
- Leetcode题解 142. Linked List Cycle II
- LeetCode 141 Linked List Cycle题解
- leetcode题解-141. Linked List Cycle
- leetcode题解-142. Linked List Cycle II
- leetcode题解-141. Linked List Cycle
- leetcode题解-142. Linked List Cycle II
- leetcode Linked List Cycle & Linked List Cycle ||
- 安卓开发——错误提示:Your content must have a ListView whose id attribute is 'android.R.id.list'
- 6、贝叶斯
- hdu 5285 wyh2000 and pupil【二分图+染色法】
- 顺序表应用5:有序顺序表归并
- IoAttachDeviceToDeviceStack routine
- LeetCode题解:Linked List Cycle
- poj 1458 最长公共子序列
- Android总结篇系列:Activity Intent Flags及Task相关属性
- Vim 粘贴板
- linux 信号 回收子进程
- 6.1、贝叶斯分类器
- windows apache服务器配置多域名
- hdoj 3336 Count the string 【KMP】
- 简单验证码的有关知识点