Tag: style blog color Io AR for SP Div 2014
[Question]
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
Question]
Determines whether a one-way linked list has loops.
[Idea]
Maintain the two pointers P1 and P2. Each time P1 moves one step forward, P2 moves two steps forward.
If P2 can catch up with P1, it indicates that the linked list has a ring.
[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) {listnode * P1 = head; listnode * P2 = head; while (P2) {// P1 move forward step p1 = p1-> next; // P2 move forward two P2 = P2-> next; If (P2) P2 = P2-> next; // infer whether P2 has caught up with P1 if (P2 & p2 = p1) return true;} return false ;}};
Leetcode: linked list cycle [1, 141]