Day006:Linked List Cycle II

来源:互联网 发布:实名认证数据网 编辑:程序博客网 时间:2024/06/06 18:30

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;            }        }    }};
0 0
原创粉丝点击