首页 > 代码库 > [leetcode]Linked List Cycle
[leetcode]Linked List Cycle
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?
算法
思路1:
快慢指针,当两个指针相遇,则表示有环,否则则无环,可能需要多遍遍历,空间复杂度O(1),时间复杂度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 }
思路2:
hash表,当某个节点有两个前驱,则该节点是环的起点,而且只需一次遍历,空间复杂度O(n),时间复杂度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 }
思路2同样是Linked List Cycle II的解法
ListNode的结构如下:
1 public class ListNode {2 int val;3 ListNode next;4 ListNode(int x){5 val = x;6 next = null;7 }8 }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。