This is a follow-on to a previous post. I am now looking at how to insert a first node into an empty doubly-linked list. It’s kind of tricky at first it seems…i would be grateful for a hint as to what is missing in my addFirst method
...
public DLL()
{
first = null ;
last = null ;
}
...
DLL myList = new DLL() ;
DLLNode A = new DLLNode("Hello", null, null) ;
...
myList.addFirst(A) ;
...
public void addFirst(DLLNode v)
{
v.pred = first ;
v.succ = last ;
}
[EDIT]
Solution as proposed by typo.pl:
public void addFirst(DLLNode v)
{
v.pred = first ;
v.succ = last ;
first = v ;
last = v ;
}
You’ve only updated the node’s information.
Now you need to update the DLL’s information as to what the first/last nodes in the list are. And it’s really easy to update when you’re adding one node to an empty list. There’s only one choice for first node and one choice for last node.