• LeetCode141LinkedListCycle和142LinkedListCycleII


    141题:判断链表是不是存在环!

     1 // 不能使用额外的存储空间
     2     public boolean hasCycle(ListNode head) {
     3         // 如果存在环的 两个指针用不一样的速度 会相遇
     4         ListNode fastNode = head;
     5         ListNode slowNode = head;
     6         while (fastNode != null && fastNode.next != null) {
     7             fastNode = fastNode.next.next;
     8             slowNode = slowNode.next;
     9             if (fastNode == slowNode) {
    10                 return true;
    11             }
    12         }
    13         return false;
    14     }

    142 给定一个链表,返回链表环开始的地方,如果没有环,就返回空。

    思路:链表头结点到链表环开始的地方的步数和两个链表相遇的地方到链表开始的地方的步数是一样多的!

     1 // 如果有环,相遇的时候与起点相差的步数等于从head到起点的步数
     2     public ListNode detectCycle(ListNode head) {
     3         ListNode pre = head;
     4         ListNode slow = head;
     5         ListNode fast = head;
     6         while (fast != null && fast.next != null) {
     7             fast = fast.next.next;
     8             slow = slow.next;
     9             if (slow == fast) {
    10                 while (pre != slow) {
    11                     slow = slow.next;
    12                     pre = pre.next;
    13                 }
    14                 return pre;
    15             }
    16         }
    17         return null;
    18     }
  • 相关阅读:
    O'Reilly总裁提姆奥莱理:什么是Web 2.0
    在MFC程序中显示JPG/GIF图像
    VC窗体设计集锦
    VxWorks使用说明书
    关于双缓冲绘图之二
    如何将EVC4工程升级到VS.NET2005工程
    某个正在运行的程序的CPU占用率
    如何去掉回车键和取消键
    探索NTFS
    ARM上的C编程
  • 原文地址:https://www.cnblogs.com/ntbww93/p/9103003.html
Copyright © 2020-2023  润新知