zoukankan      html  css  js  c++  java
  • 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?

    判断一个单链表是否有环

    解法一:记录下来遍历过的节点,但是当节点很多事会非常耗费时间,代码效率低

    C#代码

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     public int val;
     *     public ListNode next;
     *     public ListNode(int x) {
     *         val = x;
     *         next = null;
     *     }
     * }
     */
    public class Solution {
        public bool HasCycle(ListNode head) {
            List<ListNode> nodeList = new List<ListNode>();
            while(head != null)
            {
                if(nodeList.Contains(head))
                {
                    return false;
                }
                nodeList.Add(head);
                head = head.next;
            }
            return true;
        }
    }

    解法二:快慢指针,用两个指针,一个每次走一步,一个每次走两步,如果两个指针最终遇到,则说明是有环;如果遇到为NULL的指针则说明不存在环(因为是单链表)

    C代码

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     struct ListNode *next;
     * };
     */
    bool hasCycle(struct ListNode *head) {
        struct ListNode * fast = head;
        struct ListNode * slow = head;
        while(fast != NULL && slow != NULL)
        {
            fast = fast->next;
            slow = slow->next;
            if(fast != NULL)
            {
                fast = fast->next;
            }
            else
            {
                return false;
            }
            
            if(fast == slow)
            {
                return true;
            }
        }
        return false;
        
    }
  • 相关阅读:
    A. k-rounding
    哗啦啦村的刁难(4)
    喵哈哈村的种花魔法
    喵哈哈村的赛马比赛
    喵哈哈村的括号序列
    喵哈哈村的排队
    python中递归调用
    python-中函数的参数
    shell中参数及带色彩打印
    python-文件读写
  • 原文地址:https://www.cnblogs.com/Anthony-Wang/p/5302543.html
Copyright © 2011-2022 走看看