Leetcode Linked List Cycle

您所在的位置:网站首页 阿里云模板 Leetcode Linked List Cycle

Leetcode Linked List Cycle

2023-03-31 20:09| 来源: 网络整理| 查看: 265

Given a linked list, determine if it has a cycle in it.

Follow up:Can you solve it without using extra space?

Difficulty: Easy

Solution 1: HashSet

/** * 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) { HashSet set = new HashSet(); while(head!=null){ if(set.contains(head)) return true; set.add(head); head = head.next; } return false; }}Solution 2: Two pointers

/** * 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 || head.next == null) return false; ListNode curr = head.next; ListNode currTwo = head.next.next; while(currTwo != null){ if(curr == currTwo) return true; if(currTwo.next == null) return false; curr = curr.next; currTwo = currTwo.next.next; } return false; }}

0 0 leetcode Linked List Cycle & Linked List Cycle || 【LeetCode】Linked List Cycle Leetcode: Linked List Cycle Leetcode Linked List Cycle Leetcode: Linked List Cycle LeetCode:Linked List Cycle [LeetCode]Linked List Cycle LeetCode | Linked List Cycle Leetcode: Linked List Cycle LeetCode: Linked List Cycle LeetCode - Linked List Cycle [LeetCode] - Linked List Cycle LeetCode - Linked List Cycle [LeetCode]Linked List Cycle 【LeetCode】Linked List Cycle Linked List Cycle - LeetCode 【LeetCode】Linked List Cycle Linked List Cycle -- LeetCode VS未找到与约束ContractName Microsoft.VisualStudio.Text.ITextDocumentFactoryService window下执行.sh文件的方法 HDU 4608 I-number(暴力模拟) 三维几何专题 Retrofit源码分析 Leetcode Linked List Cycle 关于ios9 是否允许横竖屏设置,以及状态栏颜色设置 read obj in matlab android_java.lang.IllegalStateException: Fragment bb{42261900} not attached to Activity HDU 2333Assemble(简单二分) LeetCode--No.171--Excel Sheet Column Number LeetCode--No.357--Count Numbers with Unique Digits Next Larger Value in BST 软件概要设计与详细设计的区别


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3