142. Linked List Cycle II

来源:互联网 发布:视频噪声消除软件 编辑:程序博客网 时间:2024/05/12 02:00

先看141. Linked List Cycle 。
Given a linked list, determine if it has a cycle in it.
判断链表是否有环,用两个快慢指针移动看是否重合即可。

class Solution {public:    bool hasCycle(ListNode *head) {        ListNode *first=head,*sec=head;        while(first!=NULL&&sec!=NULL&&sec->next!=NULL){            first=first->next;            sec=sec->next->next;            if(first==sec)                return true;        }        return false;    }};

题目142,不仅需要判断是否有环,还需要求环的入口结点。
如果允许使用额外的空间的话。

class Solution {public:    ListNode *detectCycle(ListNode *head) {        map<ListNode*,bool>;        while(head!=NULL){            if(v[head]==true)                return head;            v[head]=true;            head=head->next;        }        return NULL;    }};

如果不用额外空间的话,同样需要两个指针。
当快慢指针相遇时,把快指针设置为头结点,
然后快慢指针都每次向前走一步,相遇时即为环的入口。

class Solution {public:    ListNode *detectCycle(ListNode *head) {        ListNode *first=head,*sec=head;        int fla=1;        while(first!=NULL&&sec!=NULL&&sec->next!=NULL){            first=first->next;            sec=sec->next->next;            if(first==sec){                fla=0;                break;            }        }        if(fla)            return NULL;        sec=head;        while(sec!=NULL&&first!=NULL){            if(sec==first)break;            sec=sec->next;            first=first->next;        }        return first;    }};
0 0
原创粉丝点击