Advertisement
Guest User

Untitled

a guest
Jul 22nd, 2014
211
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.16 KB | None | 0 0
  1. public class DetectLoopExistance<E> {
  2.  
  3. private Node<E> first;
  4. private Node<E> last;
  5.  
  6. public void add(E element) {
  7. final Node<E> l = last;
  8. final Node<E> newNode = new Node<E>(element, null);
  9. last = newNode;
  10. if (first == null) {
  11. first = newNode;
  12. } else {
  13. l.next = newNode;
  14. }
  15. }
  16.  
  17. private static class Node<E> {
  18. E element;
  19. Node<E> next;
  20.  
  21. Node(E element, Node<E> next) {
  22. this.element = element;
  23. this.next = next;
  24. }
  25. }
  26.  
  27.  
  28. public boolean hasLoop() {
  29. Node<E> fast = first;
  30. Node<E> slow = first;
  31.  
  32. while (fast != null && fast.next != null) {
  33. fast = fast.next.next;
  34. slow = slow.next;
  35. if (slow == fast) {
  36. return true;
  37. }
  38. }
  39. return false;
  40. }
  41. }
  42.  
  43. public boolean hasLoop() {
  44. Node<E> fast = first;
  45. Node<E> slow = first;
  46.  
  47. while (fast != null && fast.next != null) {
  48. if (slow == fast.next || slow == fast.next.next) {
  49. return true;
  50. } else {
  51. fast = fast.next.next;
  52. slow = slow.next;
  53. }
  54. }
  55. return false;
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement