LeetCode: Linked List Cycle

双指针的简单题

 1 /**

 2  * Definition for singly-linked list.

 3  * struct ListNode {

 4  *     int val;

 5  *     ListNode *next;

 6  *     ListNode(int x) : val(x), next(NULL) {}

 7  * };

 8  */

 9 class Solution {

10 public:

11     bool hasCycle(ListNode *head) {

12         // IMPORTANT: Please reset any member data you declared, as

13         // the same Solution instance will be reused for each test case.

14         if (head == NULL) return false;

15         ListNode *p, *q;

16         p = q = head;

17         while (q) {

18             q = q->next;

19             if (q == NULL) break;

20             if (p == q) return true;

21             p = p->next;

22             q = q->next;

23         }

24         return false;

25     }

26 };

 C#

 1 /**

 2  * Definition for singly-linked list.

 3  * public class ListNode {

 4  *     public int val;

 5  *     public ListNode next;

 6  *     public ListNode(int x) {

 7  *         val = x;

 8  *         next = null;

 9  *     }

10  * }

11  */

12 public class Solution {

13     public bool HasCycle(ListNode head) {

14         if (head == null) return false;

15         ListNode p = head, q = head;

16         while (q != null) {

17             q = q.next;

18             if (q == null) break;

19             if (p == q) return true;

20             p = p.next;

21             q = q.next;

22         }

23         return false;

24     }

25 }
View Code

 

你可能感兴趣的:(LeetCode)