0
0

initial commit

This commit is contained in:
23 changed files with 667 additions and 0 deletions

4
list/build.gradle Normal file
View File

@@ -0,0 +1,4 @@
plugins {
id 'myproject.java-conventions'
id 'java-library'
}

View File

@@ -0,0 +1,3 @@
module org.gradle.sample.list {
exports org.gradle.sample.list;
}

View File

@@ -0,0 +1,78 @@
package org.gradle.sample.list;
public class LinkedList {
private Node head;
public void add(String element) {
Node newNode = new Node(element);
Node it = tail(head);
if (it == null) {
head = newNode;
} else {
it.next = newNode;
}
}
private static Node tail(Node head) {
Node it;
for (it = head; it != null && it.next != null; it = it.next) {}
return it;
}
public boolean remove(String element) {
boolean result = false;
Node previousIt = null;
Node it = null;
for (it = head; !result && it != null; previousIt = it, it = it.next) {
if (0 == element.compareTo(it.data)) {
result = true;
unlink(previousIt, it);
break;
}
}
return result;
}
private void unlink(Node previousIt, Node currentIt) {
if (currentIt == head) {
head = currentIt.next;
} else {
previousIt.next = currentIt.next;
}
}
public int size() {
int size = 0;
for (Node it = head; it != null; ++size, it = it.next) {}
return size;
}
public String get(int index) {
Node it = head;
while (index > 0 && it != null) {
it = it.next;
index--;
}
if (it == null) {
throw new IndexOutOfBoundsException("Index is out of range");
}
return it.data;
}
private static class Node {
final String data;
Node next;
Node(String data) {
this.data = data;
}
}
}

View File

@@ -0,0 +1,47 @@
package org.gradle.sample.list;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class LinkedListTest {
@Test public void testConstructor() {
LinkedList list = new LinkedList();
assertEquals(0, list.size());
}
@Test public void testAdd() {
LinkedList list = new LinkedList();
list.add("one");
assertEquals(1, list.size());
assertEquals("one", list.get(0));
list.add("two");
assertEquals(2, list.size());
assertEquals("two", list.get(1));
}
@Test public void testRemove() {
LinkedList list = new LinkedList();
list.add("one");
list.add("two");
assertTrue(list.remove("one"));
assertEquals(1, list.size());
assertEquals("two", list.get(0));
assertTrue(list.remove("two"));
assertEquals(0, list.size());
}
@Test public void testRemoveMissing() {
LinkedList list = new LinkedList();
list.add("one");
list.add("two");
assertFalse(list.remove("three"));
assertEquals(2, list.size());
}
}