Try   HackMD

【LeetCode】 141. Linked List Cycle

Description

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

To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.

給一linked list,判斷裡面有沒有cycle。

我們用一個整數pos去代表linked list的尾巴指回linked list前面的哪個位置,如果pos為-1,代表裡面沒有cycle。

Example:

Example 1:

Input: head = [3,2,0,-4], pos = 1
Output: true
Explanation: There is a cycle in the linked list, where tail connects to the second node.

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

Example 2:

Input: head = [1,2], pos = 0
Output: true
Explanation: There is a cycle in the linked list, where tail connects to the first node.

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

Example 3:

Input: head = [1], pos = -1
Output: false
Explanation: There is no cycle in the linked list.

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →

Solution

  • 你可能覺得去判斷pos就好,但是你當然拿不到這個變數。
  • 去用兩個點指向頭,一個一次走一步,一個一次走兩步。如果兩個走到同一個點,代表linked list裡面有cycle
  • 需要小心指到null的時候不能再跑向下一個。

Code

/** * 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)return false; ListNode* one=head->next; ListNode* two=head->next; if(!one)return false; two = two->next; if(!two)return false; for(;one&&two;one=one->next,two=two->next) { two=two->next; if(!two)return false; if(one==two)return true; } return false; } };
tags: LeetCode C++