zoukankan      html  css  js  c++  java
  • 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     }
  • 相关阅读:
    超时检测
    非阻塞IO
    阻塞IO
    IO的概念
    http_server实例代码
    套接字中的recv与send的注意事项
    tcp流式套接字和udp数据报套接字编程区别
    TCP的粘包
    socket创建UDP服务端和客户端
    面向连接与面向非连接的传输服务区别
  • 原文地址:https://www.cnblogs.com/ntbww93/p/9103003.html
Copyright © 2011-2022 走看看