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

    思路:1.两个指针,一个走1步,一个走2步,如果相遇则有环

    注意: 在使用p->next时,一定要判断p是否为空。使用p->next->next时,检查p->next是否为空

    2.还有一种方法是用递归哈哈哈。检查

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        bool hasCycle(ListNode *head) {
            ListNode *p1 = head;
            ListNode *p2 = head;
            while(p1 && p2 && p2->next){
                p1=p1->next;
                p2=p2->next->next;
                if(p1==p2) return true;
            }
            return false;
        }
    };
  • 相关阅读:
    Manjaro中添加gitee的公钥部署
    另类的linux系统
    mac的快捷键flykey应用
    tidb总览
    raft算法
    tidb的tidb
    tidb的tikv
    tidb的pd
    切尔诺贝利事故
    血钻
  • 原文地址:https://www.cnblogs.com/renrenbinbin/p/4340229.html
Copyright © 2011-2022 走看看