Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class DetectLoopExistance<E> {
- private Node<E> first;
- private Node<E> last;
- public void add(E element) {
- final Node<E> l = last;
- final Node<E> newNode = new Node<E>(element, null);
- last = newNode;
- if (first == null) {
- first = newNode;
- } else {
- l.next = newNode;
- }
- }
- private static class Node<E> {
- E element;
- Node<E> next;
- Node(E element, Node<E> next) {
- this.element = element;
- this.next = next;
- }
- }
- public boolean hasLoop() {
- Node<E> fast = first;
- Node<E> slow = first;
- while (fast != null && fast.next != null) {
- fast = fast.next.next;
- slow = slow.next;
- if (slow == fast) {
- return true;
- }
- }
- return false;
- }
- }
- public boolean hasLoop() {
- Node<E> fast = first;
- Node<E> slow = first;
- while (fast != null && fast.next != null) {
- if (slow == fast.next || slow == fast.next.next) {
- return true;
- } else {
- fast = fast.next.next;
- slow = slow.next;
- }
- }
- return false;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement