【面试题】判断链表中是否有环

来源:互联网 发布:win10关闭网络唤醒 编辑:程序博客网 时间:2024/05/03 17:54

1. 快慢指针

/** * 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* fast=head,*slow=head;        if(!head) return false;                while(fast->next && fast->next->next)        {            fast=fast->next->next;            slow=slow->next;            if(fast==slow)                return true;        }        return false;    }};
2. 保存已经遍历节点的地址,移动下一个节点时,判断地址是否存在过

class Solution {public:    bool hasCycle(ListNode *head) {        if(!head) return false;                set<ListNode*> se;        while(head)        {            if(se.find(head)!=se.end())                return true;            else                se.insert(head);                            head=head->next;        }        return false;            }};

3. 如果可以改变链表的结构,将后一个指针指向前一个节点,如果最后回到初始节点,说明有环

class Solution {public:    bool hasCycle(ListNode *head) {        if(!head) return false;                ListNode* start=head;                ListNode* pcurr=head;        ListNode* pnext=head->next;        while(pnext)        {            if(pnext==start)                return true;                            ListNode* temp=pnext->next;            pnext->next=pcurr;                        pcurr=pnext;            pnext=temp;        }        return false;            }};



0 0