Linked List Cycle:判断链表是否有环

来源:互联网 发布:windows怎么修改快捷键 编辑:程序博客网 时间:2024/05/31 04:03

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

Follow up:

Can you solve it without using extra space?


解释:题目言简意赅,判断是否有环。

有三种情况:无环、中途有环、首尾相接


思路一: 遍历全链,每个已遍历节点存入hash表中,发生冲突即为有环。

时间复杂度:O(n) 遍历全表

空间复杂风度:O(n) hash表存储全链

  public boolean hasCycle(ListNode head) {       Set<ListNode> nodesSeen = new HashSet<>();    while (head != null) {        if (nodesSeen.contains(head)) {            return true;        } else {            nodesSeen.add(head);        }        head = head.next;    }    return false;    }



思路二:两个指针:fast每次移动两格,slow每次移动一格。若存在环,则在O(K)时间内fast可追上slow,K为环的长度。再加上未进入环时所耗时O(N),时间复杂度O(N+K),即O(N)

空间复杂度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)||head.next==null) return false;        ListNode fast = head.next;        ListNode slow = head;        while(fast!=slow){            if(fast.next==null||fast.next.next==null) return false;            fast = fast.next.next;            slow = slow.next;        }        return true;    }}





阅读全文
0 0
原创粉丝点击