zoukankan      html  css  js  c++  java
  • LeetCode: Linked List Cycle

    双指针的简单题

     1 /**
     2  * Definition for singly-linked list.
     3  * struct ListNode {
     4  *     int val;
     5  *     ListNode *next;
     6  *     ListNode(int x) : val(x), next(NULL) {}
     7  * };
     8  */
     9 class Solution {
    10 public:
    11     bool hasCycle(ListNode *head) {
    12         // IMPORTANT: Please reset any member data you declared, as
    13         // the same Solution instance will be reused for each test case.
    14         if (head == NULL) return false;
    15         ListNode *p, *q;
    16         p = q = head;
    17         while (q) {
    18             q = q->next;
    19             if (q == NULL) break;
    20             if (p == q) return true;
    21             p = p->next;
    22             q = q->next;
    23         }
    24         return false;
    25     }
    26 };

     C#

     1 /**
     2  * Definition for singly-linked list.
     3  * public class ListNode {
     4  *     public int val;
     5  *     public ListNode next;
     6  *     public ListNode(int x) {
     7  *         val = x;
     8  *         next = null;
     9  *     }
    10  * }
    11  */
    12 public class Solution {
    13     public bool HasCycle(ListNode head) {
    14         if (head == null) return false;
    15         ListNode p = head, q = head;
    16         while (q != null) {
    17             q = q.next;
    18             if (q == null) break;
    19             if (p == q) return true;
    20             p = p.next;
    21             q = q.next;
    22         }
    23         return false;
    24     }
    25 }
    View Code
  • 相关阅读:
    密码学常用解码网站
    macOS VMware Fusion 中 vmtools为灰色
    XSS-Payloads
    Tomcat 漏洞总结
    mac 更新完Big Sur需重新配置项目
    sqlmap的使用 ---- 自带绕过脚本tamper
    FTP 日志分析
    CentOS Java环境问题
    Nginx 学习
    英语学习-邮件表达方法 例句
  • 原文地址:https://www.cnblogs.com/yingzhongwen/p/3423135.html
Copyright © 2011-2022 走看看