I am working on trying to make my doubly linked list use tail recursion.
public class DoublyLinkedList
{
private int noOfItems;
private DLLNode head;
private DLLNode tail;
// Default constructor
public DoublyLinkedList()
{
head = null;
tail = null;
this.noOfItems = 0;
}
public void AddItem(String value)
{
DLLNode newNode = new DLLNode(value);
if (head == null)
{
head = newNode;
noOfItems++;
}
else {
DLLNode current = head;
while(current != null) {
if (current.GetNextNode() == null) {
current.setNextNode(newNode);
newNode.setPrevious(newNode);
noOfItems++;
break;
}
current = current.GetNextNode();
}
}
}
}
My Node class is as follows:
public class DLLNode
{
private DLLNode previous;
public DLLNode next;
private String value;
public DLLNode(String value)
{
this.value = value;
}
/* This method returns the String item of data held in this node */
public String GetDataItem()
{
return value;
}
public void setDataItem()
{
this.value = value;
}
/* This method returns the node immediately prior to this node in the list or
* null if there is no such node */
public DLLNode GetPreviousNode()
{
return previous;
}
public void setPrevious(DLLNode previous)
{
this.previous = previous;
}
/* This method returns the node immediately after this node in the list or null
* if there is no such node. */
public DLLNode GetNextNode()
{
return next;
}
public void setNextNode(DLLNode next)
{
this.next = next;
}
public void AddItem(String value)
{
if (next == null)
{
next = new DLLNode(value);
}
else
next.AddItem(value);
}
}
This is the code I have for my Add Item. I have also attempted to make this use tail recursion which is the code shown below:
public void AddItem(String value)
{
if (head == null)
{
head = new DLLNode(value);
noOfItems++;
}
else {
head.AddItem(value);
}
}
The recursive version I have written works. However it isn't doubly linked.
I understand that for it to be a doubly linked list a node needs to know what comes next and what has come before it. So in my Add Item do I need something to let the next node know what has come before it? If so any advice on how to do this?
Thanks in Advance.
addItem()andDLLNodeSounds picky, but we get confused if we see a method that looks like a class or a constructor!