Question

I want to insert a Node in to the middle of a doubly linked list.This is my implementation.
My default argument is the node before the to-be inserted node .

public class DListNode{
    public DListNode prev,next;
    public Object item;
    public DListNode(Object i,DListNode n,DListNode p){
        prev=p;
        next=n;
        item=i;     
    }
    public DListNode(Object i){
        this(i,null,null);  
    }
}  

public void insertAfter(Object e,DListNode firstNode) throws UnderFlow{
        if(isEmpty()||(head==tail))
            throw new UnderFlow("need at least two nodes");
        else{
            DListNode v=firstNode.next;
            DListNode k=new DListNode(e,v,firstNode);
            firstNode =k;
            v.prev=k;
        }
    }

 public static void main (String args[]) throws UnderFlow{
        DList d=new DList();

         d.insertFront("d");
         d.insertFront("b");

        d.insertAfter("c",d.head);

        System.out.println(d.toString());

    }  

Though I can't see where I am making the mistake it only prints out b,d.
c is not inserted in the middle.
Please can someone point out where I am making the mistake

Was it helpful?

Solution

I would suggest you to use variable names with some meaning. Your names like k, v are terrible to understand

Instead of firstNode =k; should be firstNode.next =k; but it's better to rewrite with proper names. Like this

DListNode next=firstNode.next;
DListNode newOne=new DListNode(e,next,firstNode);
firstNode.next =newOne;
next.prev=newOne;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top