[Leetcode] linked list cycle

Source: Internet
Author: User

Linked List cycle

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

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

Algorithm

Thought 1:

Fast and slow pointers. When two pointers meet each other, it indicates that there is a ring. Otherwise, there is no ring. It may need to be traversed multiple times. The space complexity is O (1), and the time complexity is O (n)

 1 public class Solution { 2     public boolean hasCycle(ListNode head) { 3         if(head == null) return false; 4         ListNode fast = head; 5         ListNode slow = head; 6         while(true){ 7             if(fast.next == null || fast.next.next == null) return false; 8             fast = fast.next.next; 9             slow = slow.next;10             if(fast == slow) return true;11         }12     }13 }

 

Idea 2:

Hash table. When a node has two prefixes, the node is the starting point of the ring and only needs to be traversed once. The space complexity is O (n), and the time complexity is O (n)

 1 public class Solution { 2     public boolean hasCycle(ListNode head) { 3         if(head == null) return false; 4         ListNode tem = new ListNode(0); 5         tem.next = head; 6         Map<ListNode,ListNode> hash = new HashMap<ListNode,ListNode>(); 7         while(true){ 8             if(tem.next == null) return false; 9             if(hash.get(tem.next) != null) return true;10             hash.put(tem.next,tem);11             tem = tem.next;12         }13     }14 }

Idea 2 is the solution of linked list cycle II.

 

The listnode structure is as follows:

1 public class ListNode {2     int val;3     ListNode next;4     ListNode(int x){5         val = x;6         next = null;7     }8 }
View code

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.