101k views
1 vote
Public void addData (int index, T newData) throws InvalidPositionException. This method must add a new node to the list storing newData. The node must be inserted in the index position of the list. Therefore, if index = 0 then the new node must be inserted at the beginning of the list. If index = 1, the new node is added after the first node in the list; if index = 2, then the new node is added after the second node of the list, and so on. If index = numDataItems, then the new node is added to the end of the list. If index < 0 or index > numDataItems an InvalidPositionException must be thrown.

1 Answer

3 votes

Answer:

DoubleList()

{

numElements=0;

front=rear=null;

}

public void addData(int index,T newData) throws InvalidPositionException

{

if(index<0||index>numElements)

throw new InvalidPositionException();

DoubleNode newNode=new DoubleNode(newData);

numElements++;

// if there is no node initially

if(front==null)

{

front=rear=newNode;

return;

}

// get the node after which we have to add the new node

DoubleNode pre=null,temp=front;

while(temp!=null&&index>0)

{

pre=temp;

temp=temp.next;

index--;

}

if(pre==null)

{

newNode.next=front;

front.previous=newNode;

front=newNode;

}

else

{

newNode.next=temp;

newNode.previous=pre;

pre.next=newNode;

}

}

public DoubleNode<T> getNode(int index)

{

if(index<0||index>=numElements)

try {

throw new InvalidPositionException();

} catch (InvalidPositionException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

DoubleNode temp=front;

// traverse the list till we reach at the given index and return the address of that node

while(temp!=null&&index>0)

{

temp=temp.next;

index--;

}

return temp;

}

public void removeData(int index) throws InvalidPositionException

{

DoubleNode temp;

temp = getNode(index); // get the reference to the node at the given index

numElements--;

// if there is only one node in the linkedlist then after removing there is no node

if(numElements==0)

{

front=rear=null;

}

else

{

temp.previous.next=temp.next;

if(temp.next!=null)

temp.next.previous=temp.previous;

}

}

public T getData(int index) throws InvalidPositionException

{

DoubleNode temp=null;

temp = getNode(index); // get the Node from where we have to get the data

return (T) temp.data;

}

public void setData(int index ,T newData) throws InvalidPositionException

{

DoubleNode temp;

temp = getNode(index); // get the node where we have to set the newData

temp.data=newData;

}

Step-by-step explanation:

See the complete code in answer section.

User Dvancouver
by
3.6k points