leetcode刷题日记—— Linked List Cycle II

来源:互联网 发布:seo是什么意思 编辑:程序博客网 时间:2024/06/05 21:13
Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

Note: Do not modify the linked list.

Follow up:

Can you solve it without using extra space?

问题分析:这个题目和之前的题目类似,都是判断是否是循环链表。并返回节点。但是这里要求不能够改变链表。所以之前的那种方式不再适用。这里采用双指针的方式,一个指针的移动速度是另外一个指针的二倍,如果存在循环,必然会出现相遇。但是注意相遇的节点不一定是最开始连上的那个节点。实现代码如下:

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    ListNode *detectCycle(ListNode *head) {        if(head==NULL) return NULL;        if(head->next==NULL) return NULL;        ListNode *p=head,*q=head,*m=NULL;        while(p&&q->next){            p=p->next;            q=q->next->next;            if(q==NULL) return NULL;            if(p==q)          {            q= head;            while(q!=p)             {                p= p->next;                q= q->next;            }            m= p;            break;        }                   }        return m;    }};


0 0
原创粉丝点击