首页 > 代码库 > 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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。