Description

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

  • Follow up:
    Can you solve it without using extra space?
  • 链表无环

LeetCode[141]Linked List Cycle

  • 链表有环

LeetCode[141]Linked List Cycle

链表无环

idea

  • 设定超时时间暴力穷举
    判断给定的时间内,链表是否遍历完成。
  • 使用Set判重
    遍历链表,每走一个节点都在Set中查找是否存在,若存在则链表有环。
    时间复杂度O(n)
  • 使用快慢指针
    使用一个快指针(一次走两步)和一个慢指针(一次走一步),如果两个指针相遇,则链表有环。
    时间复杂度O(n),不需要额外的存储开销,这种方法性能最佳。
/**
 - 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) {
        ListNode f = head, s =head;
        while(null != f && null != s && f.next != null) {
            s = s.next;
            f = f.next.next;
            if (s == f) {
                return true;
            }
        }
        return false;        
    }
}
  • 快慢指针执行结果
    LeetCode[141]Linked List Cycle

相关文章:

  • 2022-02-11
  • 2021-09-02
  • 2021-09-14
  • 2021-12-05
  • 2022-01-06
  • 2021-09-22
  • 2021-12-16
猜你喜欢
  • 2021-07-08
  • 2022-02-02
  • 2022-01-05
  • 2021-10-04
  • 2021-04-23
  • 2021-08-08
  • 2022-03-08
相关资源
相似解决方案