leetcode 141 Circular linked list

1. I think of using set.

/**
 * 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) {
        unordered_set<ListNode*> us;
        while(head!=NULL){
            if(us.find(head)==us.end())
                us.insert(head);
            else 
                return  true ;
            head=head->next;
        }
        return false;
    }
};

 

 

 

2. Double pointer, no extra space is used.

One with speed 2 and one with speed 1.

https://blog.csdn.net/nomasp/article/details/51598735

 

The author does not provide proof. My proof is as follows:

node == n

car = (2i+1) //%n

man= i //%n

Q:car-man==k*n ?

=>

i+1 evenly divide n

yes

 

The speed of the car is 2 and the speed of the person is 1.

If there is a ring, they may meet when they are closest, if not, the difference is 1.

Let the coordinates of cars and people be...

Q: Can the difference in coordinates be an integer multiple of the ring?

Yes, i+1 can == n

 

Code idea:

Cars go forward 2, people go forward 1.

if the coordinates are equal, true

if car==NULL || car->next ==NULL , false

Don't judge people, because cars are faster than people, and they have already judged.

 

Also, define two pointers on the same line:

ListNode *i , *j ; 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325299713&siteId=291194637