首页 > 代码库 > LeetCode Linked List Cycle

LeetCode Linked List Cycle

Given a linked list, determine if it has a cycle in it.

Follow up:
Can you solve it without using extra space?

解题思路:突发奇想,脑洞大开。回路,自然是走到已经走过的地方,如何知道这个地方已经走过,值和指针,如果用特殊标志的值的话不靠谱,因为可能某个元素就是那个值,想到用指针,保持head一直不变,如果head有后续节点,且后续节点不是自己,即head->next != head,则将下一个节点删除,且另这个被删除的节点指向head,使得如果这个节点是回路的入口,那么一定会遍历回来的。

/** * Definition for singly-linked list. * 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;        int count = 0;        while(head->next != head && head->next != NULL)        {            ListNode *q = head->next;//sava next node            head->next = head->next->next;            q->next = head;//next node of head point to head        }        if(head->next == head)return true;        else if(head->next == NULL)return false;           }};

 

LeetCode Linked List Cycle