diff --git a/src/main/java/ru/j4j/collection/RevertLinked.java b/src/main/java/ru/j4j/collection/RevertLinked.java new file mode 100644 index 0000000..60b1582 --- /dev/null +++ b/src/main/java/ru/j4j/collection/RevertLinked.java @@ -0,0 +1,69 @@ +package ru.j4j.collection; + +import java.util.Iterator; +import java.util.NoSuchElementException; + +public class RevertLinked implements Iterable { + private Node head; + + public void add(T value) { + Node node = new Node(value, null); + if (head == null) { + head = node; + return; + } + Node tail = head; + while (tail.next != null) { + tail = tail.next; + } + tail.next = node; + } + + public boolean revert() { + if (head == null || head.next == null) { + return false; + } + Node current = head; + Node prev = null; + while (current != null) { + head = current.next; + current.next = prev; + prev = current; + current = head; + } + head = prev; + return true; + } + + @Override + public Iterator iterator() { + return new Iterator() { + Node node = head; + + @Override + public boolean hasNext() { + return node != null; + } + + @Override + public T next() { + if (!hasNext()) { + throw new NoSuchElementException(); + } + T value = node.value; + node = node.next; + return value; + } + }; + } + + private static class Node { + T value; + Node next; + + public Node(T value, Node next) { + this.value = value; + this.next = next; + } + } +} \ No newline at end of file diff --git a/src/test/java/ru/j4j/collection/RevertLinkedTest.java b/src/test/java/ru/j4j/collection/RevertLinkedTest.java new file mode 100644 index 0000000..14a0924 --- /dev/null +++ b/src/test/java/ru/j4j/collection/RevertLinkedTest.java @@ -0,0 +1,37 @@ +package ru.j4j.collection; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +class RevertLinkedTest { + private RevertLinked linked; + + @BeforeEach + void init() { + linked = new RevertLinked<>(); + } + + @Test + void whenSize0ThenReturnFalse() { + assertThat(linked.revert()).isFalse(); + } + + @Test + void whenSize1ThenReturnFalse() { + linked.add(1); + assertThat(linked.revert()).isFalse(); + } + + @Test + void whenAddAndRevertTrue() { + linked.add(1); + linked.add(2); + linked.add(3); + linked.add(4); + assertThat(linked).containsSequence(1, 2, 3, 4); + assertThat(linked.revert()).isTrue(); + assertThat(linked).containsSequence(4, 3, 2, 1); + } +} \ No newline at end of file