环形链表

作者: coder_flag | 来源:发表于2018-09-27 10:57 被阅读7次

    给定一个链表,判断链表中是否有环。

    进阶:
    你能否不使用额外空间解决此题?


    解法1:

    思路: 比较六的思路,我用两指针fast和low,从头开始,一个走两步,一个走一步。
    如果有环,就一定有追上的时候。

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     struct ListNode *next;
     * };
     */
    bool hasCycle(struct ListNode* head) {
          if(head == NULL||head->next == NULL){
            return false;
        }
        struct ListNode* fast=head->next;
        struct ListNode* low=head;
        while(fast!=NULL){
            if(fast==low){
                return true;
            }else{
                fast=fast->next;
                if(fast==NULL){
                    return false;
                }else{
                    fast=fast->next;
                    low=low->next;
                }
            }   
        }
      
        return false;
    }
    



    解法2:

    思路: leetcode给出的解法:我们遍历所有结点并在哈希表中存储每个结点的引用(或内存地址)。如果当前结点为空结点 null(即已检测到链表尾部的下一个结点),那么我们已经遍历完整个链表,并且该链表不是环形链表。如果当前结点的引用已经存在于哈希表中,那么返回 true(即该链表为环形链表)

    
    public boolean hasCycle(ListNode head) {
        Set<ListNode> nodesSeen = new HashSet<>();
        while (head != null) {
            if (nodesSeen.contains(head)) {
                return true;
            } else {
                nodesSeen.add(head);
            }
            head = head.next;
        }
        return false;
    }
    

    相关文章

      网友评论

        本文标题:环形链表

        本文链接:https://www.haomeiwen.com/subject/plxeoftx.html