I realize that there are a few good threads already existing which discuss how to implement a linked list in Java, however I can't seem to find one which does not use a constructor like this,
public LinkList() {
Link = null;
}
or something along these lines. However, I have not done this in my code, and therefore I am having trouble with writing a few of the methods.
I have a class called Link which contains the following code, note without any constructor like the one displayed above:
public class Link {
private Link next = null;
private String value = null;
public Link getNext(){
return next;
}
public void setNext(Link nextLink){
next = nextLink;
}
public String getValue(){
return value;
}
public void setValue(String aValue){
value = aValue;
}
}
and then I have my LinkedList class, which contains the following code:
public class LinkedList {
private Link head = null;
private Link tail = null;
public Link getHead(){
return head;
}
public void setHead(Link aLink){
head = aLink;
}
public Link getTail(){
return tail;
}
public void setTail(Link aLink){
tail = aLink;
}
public boolean isEmpty(){
return(head == null && tail == null);
}
public void addLast(String aString){
Link link = new Link();
link.setValue(aString);
//tail.setNext(link);
if(isEmpty()){
head = link;
}else{
tail.setNext(link);
}
tail = link;
}
public void addFirst(String aString) {
Link link = new Link();
link.setValue(aString);
if(isEmpty()){
tail = link;
}else{
head.setNext(link);
}
head = link;
}
public Link removeFirst(){
Link temp = head;
head = temp.getNext();
temp.setNext(null);
return temp;
}
}
My addFirst Method, and my isEmpty Method both seem to be working but my addLast and removeFirst Methods are not. I have drawn pictures, looked at pseudo code, and searched around the internet, but I just cannot seem to figure this out.
I need to know how to get my addLast and removeFirst methods working without having to add in the constructor at the beginning like all the rest of the example code I keep seeing.
Here are the Tests they need to pass:
@Test
public void testRemoveFirst(){
list.addFirst("three");
list.addFirst("two");
list.addFirst("one");
assertTrue("one".equals(list.removeFirst()));
assertTrue("two".equals(list.removeFirst()));
assertTrue("three".equals(list.removeFirst()));
}
@Test
public void testAddLast(){
list.addFirst("three");
list.addFirst("two");
list.addFirst("one");
assertTrue( "three".equals(list.removeLast()));
assertTrue( "two".equals(list.removeLast()));
assertTrue( "one".equals(list.removeLast()));
assertNull(list.removeLast());
}
Link link = new Link();compiler will generate it for you.