diff --git a/src/SortedLinkedList.java b/src/SortedLinkedList.java old mode 100755 new mode 100644 index f75caa0..1e775b5 --- a/src/SortedLinkedList.java +++ b/src/SortedLinkedList.java @@ -1,13 +1,15 @@ public class SortedLinkedList { private Node head; - /** * Create an empty list. */ + private int length; + public SortedLinkedList() { head = null; + length = 0; } /** @@ -23,7 +25,7 @@ public void print() System.out.print(temp.getName() + ":" + temp.getQuantity() + " "); temp = temp.getNext(); } - + System.out.println(); } @@ -34,8 +36,23 @@ public void print() */ public String getName(int index) { + Node f = head; + if (f == null){ + return null; + } + if (index == 0){ + return f.getName(); + } + + for (int i = 0; i < index; i++){ + f = f.getNext(); } + return f.getName(); + } + + + /** * This method will return the quantity at the specified index. Similar to @@ -44,7 +61,18 @@ public String getName(int index) */ public int getQuantity(int index) { + if (head == null){ + return -1; + } + Node r = head; + + for (int i = 0; i < index; i++) + { + r = r.getNext(); + } + + return r.getQuantity(); } /** @@ -52,7 +80,7 @@ public int getQuantity(int index) */ public int length() { - + return length; } /** @@ -61,7 +89,15 @@ public int length() */ public boolean isMember(String name) { - + if (length == 0){ + return false; + } + else if (head.getName().equals(name)){ + return true; + } + else{ + return false; + } } /** @@ -70,6 +106,9 @@ public boolean isMember(String name) */ public void insert(String name, int quantity) { + Node newNode = new Node(name, quantity); + head = newNode; + length +=1; } } diff --git a/src/SortedLinkedListTest.java b/src/SortedLinkedListTest.java new file mode 100644 index 0000000..b95cd2f --- /dev/null +++ b/src/SortedLinkedListTest.java @@ -0,0 +1,40 @@ +import junit.framework.TestCase; + +public class SortedLinkedListTest extends TestCase { + public void testEmptyList() { + + SortedLinkedList list = new SortedLinkedList(); + + assertEquals(null, list.getName(0)); + assertEquals(-1, list.getQuantity(0)); + assertEquals(0, list.length()); + assertEquals(false, list.isMember("member")); + } + + public void testSingleNode() + { + SortedLinkedList list = new SortedLinkedList(); + list.insert ("x", 1); + + assertEquals("x", list.getName(0)); + assertEquals(1, list.getQuantity(0)); + assertEquals(1, list.length()); + assertEquals(true, list.isMember("x")); + } + + public void testSecondNode() + { + SortedLinkedList list = new SortedLinkedList(); + list.insert ("x", 1); + list.insert ("y", -1); + + assertEquals("x", list.getName(1)); + assertEquals("y", list.getName(0)); + assertEquals(1, list.getQuantity(1)); + assertEquals(-1, list.getQuantity(0)); + assertEquals(2, list.length()); + assertEquals(true, list.isMember("x")); + assertEquals(true, list.isMember("y")); + } + + } \ No newline at end of file