• 141. 链表是否成环 Linked List Cycle


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

    Follow up:
    Can you solve it without using extra space?

    题意:判断链表是否成环。

    注意:最后一个节点的next指针,有可能指向链表中任意一个节点

    方法一:使用HashSet,保存遍历过的节点的HashCode

    1. public class Solution {
    2. public bool HasCycle(ListNode head) {
    3. if (head == null) {
    4. return false;
    5. }
    6. ListNode node = head;
    7. HashSet<int> hashSet = new HashSet<int>();
    8. hashSet.Add(node.GetHashCode());
    9. while (node.next != null) {
    10. node = node.next;
    11. int hash = node.GetHashCode();
    12. if (hashSet.Contains(hash)) {
    13. return true;
    14. } else {
    15. hashSet.Add(hash);
    16. }
    17. }
    18. return false;
    19. }
    20. }
    方法二:使用两个指针,一个快一个慢,如果两个指针相遇,则链表成环
    1. public class Solution {
    2. public bool HasCycle(ListNode head) {
    3. if (head == null || head.next == null) {
    4. return false;
    5. }
    6. ListNode slow = head;
    7. ListNode fast = head;
    8. while (fast.next != null && fast.next.next != null) {
    9. slow = slow.next;
    10. fast = fast.next.next;
    11. if (slow == fast) {
    12. return true;
    13. }
    14. }
    15. return false;
    16. }
    17. }





  • 相关阅读:
    电信10兆指的是多少Mbps
    keycloak ssl-required报错问题处理
    Centos7 DNS神奇的配置
    angular4套用primeng样式
    Python库大全
    jquery根据name属性的高级选择
    Js String 属性扩展
    SQLSever 触发器
    IaaS, PaaS和SaaS
    Sql Server 基础知识
  • 原文地址:https://www.cnblogs.com/xiejunzhao/p/bff2737c2fd5663021e89538a703ca2c.html
Copyright © 2020-2023  润新知