LeetCode 142. Linked List Cycle II C++

142. Linked List Cycle II

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?

Approach

1.题目大意是问你是否能找到链表循环的开始结点。这道题首先要明白规律,就是快慢指针相遇的地方距离开始循环结点的长度等于头节点到开始循环结点的长度,你可以把它想做是循环的一部分,然后它只能被走过一次,然后就没用了,可以自己尝试画图看看。

Code

 class Solution {
 public:
     ListNode *detectCycle(ListNode *head) {
         if (head == nullptr||head->next==nullptr||head->next->next==nullptr)return nullptr;
         ListNode *slow = head, *fast = head;
         while (fast&&fast->next) {
             slow = slow->next;
             fast = fast->next->next;
             if (slow == fast)break;
         }
         if (slow != fast)return nullptr;
         while (head != slow) {
             head = head->next;
             slow = slow->next;
         }
         return head;
     }
 };

猜你喜欢

转载自blog.csdn.net/WX_ming/article/details/81987891
今日推荐