您的位置:首页 > 其它

Day006:Linked List Cycle II

2017-03-15 15:35 225 查看
Problem:

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?

Difficulty:

Solution:

Read all the node of list,k mean the k node of a list,then from the head pointer to this node,count the number of next time.if the number is equal to k,the node is not the node we need,if the number is not equal to k,we find the node,and the list is a cycle.

/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
using namespace std;
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
if (head == nullptr || head->next == nullptr){
return NULL;
}
if(head->next == head){
return head;
}
int i = 0;
int j = 0;
int k = 0;
ListNode* node=head;
ListNode* node1=nullptr;
while(true){
i = i + 1;
j = 0;
node1 = head;
while(true){
j = j+ 1;
if (node1 == node){
k = j;
break;
}
node1 = node1->next;
}
if(i != k){
return node;
}
node = node->next;
if (node == nullptr){
return NULL;
}
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: