判断是不是循环链表,如果是,返回它的第一个结点
首先判断,判断完之后,遍历循环链表,将它的指针域置为空,则循环到链表的第一个结点时,由于指针域为空,返回
#include<iostream>
#include<vector>
using namespace std;
/*
Given a linked list, return the node where the cycle begins. If there is no cycle, returnnull.
Follow up:
Can you solve it without using extra space?*/
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* faster = head;ListNode* slower = head;while (faster->next->next != NULL && faster->next != NULL) {slower = slower->next;faster = faster->next->next;if (faster == slower)return true;}return false;}
};
//class Solution { //没有通过所有测试用例
//public:
// ListNode *detectCycle(ListNode *head) {
// if (head == NULL)
// return NULL;
// ListNode* faster = head;
// ListNode* slower = head;
// while (faster->next->next != NULL && faster->next != NULL) {
// slower = slower->next;
// faster = faster->next->next;
// if (faster == slower) //当他两第一轮相同时,正好是最后一个结点
// return slower;
// }
// return NULL;
// }
//};
class Solution {
public:bool hasCycle(ListNode *head) {ListNode *fast = head;ListNode *slow = head;while (fast != NULL && fast->next != NULL) {fast = fast->next->next;slow = slow->next;if (fast == slow)return true;}return false;}ListNode *detectCycle(ListNode *head) {if (hasCycle(head)) {ListNode *temp = head;while (head->next) {temp = head->next;head->next = NULL;head = temp;}return head;}else {return NULL;}}
};