141 环形链表

  1. /**
  2. * Definition for singly-linked list.
  3. * class ListNode {
  4. * int val;
  5. * ListNode next;
  6. * ListNode(int x) {
  7. * val = x;
  8. * next = null;
  9. * }
  10. * }
  11. */
  12. public class Solution {
  13. public boolean hasCycle(ListNode head) {
  14. ListNode p, q;
  15. if (head == null) {
  16. return false;
  17. }
  18. else {
  19. q = head;
  20. p = head.next;
  21. }
  22. // 双指针法,p指针在前,步长为2, q在后,步长为1
  23. while (p != null && q != null) {
  24. if (p == q)
  25. return true;
  26. // p指针先向前迈进一步,遇到空则一定没有环
  27. p = p.next;
  28. if (p == null) {
  29. return false;
  30. }
  31. else {
  32. p = p.next;
  33. q = q.next;
  34. }
  35. }
  36. return false;
  37. }
  38. }