[Java]LeetCode141. 环形链表 | Linked List Cycle
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:https://www.cnblogs.com/strengthen/p/9714958.html
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
给定一个链表,判断链表中是否有环。
进阶:
你能否不使用额外空间解决此题?
0ms
1 /** 2 * Definition for singly-linked list. 3 * class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { 7 * val = x; 8 * next = null; 9 * } 10 * } 11 */ 12 public class Solution { 13 public boolean hasCycle(ListNode head) { 14 if(head == null) return false; 15 ListNode fast = head; 16 ListNode slow = head; 17 do{ 18 if(fast.next == null || fast.next.next == null) return false; 19 fast = fast.next.next; 20 slow = slow.next; 21 }while(fast != slow); 22 return true; 23 } 24 }
0ms
1 /** 2 * Definition for singly-linked list. 3 * class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { 7 * val = x; 8 * next = null; 9 * } 10 * } 11 */ 12 public class Solution { 13 public boolean hasCycle(ListNode head) { 14 if(head==null) return false; 15 ListNode walker = head; 16 ListNode runner = head; 17 while(runner.next!=null && runner.next.next!=null) { 18 walker = walker.next; 19 runner = runner.next.next; 20 if(walker==runner) return true; 21 } 22 return false; 23 } 24 }
1ms
1 /** 2 * Definition for singly-linked list. 3 * class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { 7 * val = x; 8 * next = null; 9 * } 10 * } 11 */ 12 public class Solution { 13 public static boolean hasCycle(ListNode head) { 14 if (head == null || head.next == null) { 15 return false; 16 } 17 ListNode slow = head; 18 ListNode fast = head.next; 19 int f = 1;//上面两行赋值已前进了一次 20 while (slow != fast) { 21 if (fast == null || fast.next == null) { 22 return false; 23 } 24 slow = slow.next; 25 fast = fast.next.next; 26 f++; 27 } 28 System.out.println("LinkedList.size:"+f); 29 return true; 30 } 31 }
4ms
1 public class Solution { 2 public boolean hasCycle(ListNode head) { 3 HashSet<ListNode> visited = new HashSet<>(); 4 5 ListNode curr = head; 6 while (curr != null) { 7 if (visited.contains(curr)) 8 return true; 9 visited.add(curr); 10 curr = curr.next; 11 } 12 13 return false; 14 } 15 }
5ms
1 /** 2 * Definition for singly-linked list. 3 * class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { 7 * val = x; 8 * next = null; 9 * } 10 * } 11 */ 12 public class Solution { 13 public boolean hasCycle(ListNode head) { 14 Set<ListNode> set = new HashSet<>(); 15 while(head != null){ 16 if(set.contains(head)){ 17 return true; 18 } else{ 19 set.add(head); 20 } 21 head = head.next; 22 } 23 return false; 24 } 25 }