美文网首页
141. 环形链表

141. 环形链表

作者: 青洺想吃棒棒糖 | 来源:发表于2019-02-18 20:10 被阅读0次

https://leetcode-cn.com/problems/linked-list-cycle/
给定一个链表,判断链表中是否有环。
为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -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) {
        map<ListNode*,int> ma;
        while(head!=NULL){
            if(ma[head]!=1){
                ma[head]=1;
                head=head->next;
            }
            else{
                return true;
            }
        }
        return false;
    }
};

改进:使用快慢指针,若指针相遇则判断有环

/**
 * 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) {
        if(head==NULL)
            return false;
        ListNode *p1=head,*p2=head->next;    
        while(p1!=p2){
            if(p2==NULL||p2->next==NULL)
                return false;
            p1=p1->next;
            p2=(p2->next)->next;
        }
        return true;
    }
}; 

相关文章

网友评论

      本文标题:141. 环形链表

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