Skip to content

Commit

Permalink
6. Перевернуть связанный список [#161 #182935]
Browse files Browse the repository at this point in the history
  • Loading branch information
Temzor committed Jul 9, 2024
1 parent 2176f87 commit c330ceb
Show file tree
Hide file tree
Showing 2 changed files with 106 additions and 0 deletions.
69 changes: 69 additions & 0 deletions src/main/java/ru/j4j/collection/RevertLinked.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
package ru.j4j.collection;

import java.util.Iterator;
import java.util.NoSuchElementException;

public class RevertLinked<T> implements Iterable<T> {
private Node<T> head;

public void add(T value) {
Node<T> node = new Node<T>(value, null);
if (head == null) {
head = node;
return;
}
Node<T> tail = head;
while (tail.next != null) {
tail = tail.next;
}
tail.next = node;
}

public boolean revert() {
if (head == null || head.next == null) {
return false;
}
Node<T> current = head;
Node<T> prev = null;
while (current != null) {
head = current.next;
current.next = prev;
prev = current;
current = head;
}
head = prev;
return true;
}

@Override
public Iterator<T> iterator() {
return new Iterator<T>() {
Node<T> 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> {
T value;
Node<T> next;

public Node(T value, Node<T> next) {
this.value = value;
this.next = next;
}
}
}
37 changes: 37 additions & 0 deletions src/test/java/ru/j4j/collection/RevertLinkedTest.java
Original file line number Diff line number Diff line change
@@ -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<Integer> 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);
}
}

0 comments on commit c330ceb

Please sign in to comment.