leetcode 9:linked-list-cycle-ii

题目描述

对于一个给定的链表,返回环的入口节点,如果没有环,返回null
拓展:
你能给出不利用额外空间的解法么?
题目分析:
这属于常规问题,利用快慢指针获取环的入口节点。
代码如下:
 1 ListNode *detectCycle(ListNode *head) {
 2         if(head == nullptr)
 3             return nullptr;
 4         ListNode* fast = head;
 5         ListNode* slow = head;
 6         while(fast->next != NULL && fast->next->next != NULL)
 7         {
 8             slow = slow->next;
 9             fast = fast->next->next;
10             if(fast == slow){
11                 ListNode* node1 = head;
12                 ListNode* node2 = fast;
13                 while(node1 != node2){
14                     node1 = node1->next;
15                     node2 = node2->next;
16                 }
17                 return node1;
18             }
19         }
20         return nullptr;
21     }

 

posted @ 2020-08-13 14:41  请叫我小小兽  阅读(97)  评论(0编辑  收藏  举报