In: Computer Science
hi guys, could someone tell my where this is going wrong please, its adding into a double linked list, i have another method to add at the end which is working but the rest of this??
thanks
public boolean add(int index, Token obj) {
if(obj == null) {
throw new
NullPointerException();
}
if (index < 0 || index >
this.size()-1) {
throw new
IndexOutOfBoundsException();
}
// new node to add
Node toADD = new
Node(null,null,obj);
//insert at the beginning of the
list
if(index == 0) {
// make the next
of the new node point to the previous head, and previous to
null
toADD.next =
head;
toADD.prev =
null;
//change the
previous of head to the new node
if(head != null)
{
head.prev = toADD;
// set the new
node to be the head;
head =
toADD;
size++;
}
if(index >1) {
for(int i =1;
i<= index; i++ ) {
if(index == i) {
Node oldNode =
this.getNode(i);
toADD.prev =
oldNode.prev;
oldNode.prev = toADD;
toADD.next = oldNode;
toADD.prev.next =
oldNode;
size++;
}
if(index == this.size()-1) {
this.add(obj);
I can't See Your Full Code so, i can't Judge where You are doing wrong But to add At From Of doubly linked list simply do This.
// Adding a node at the front of the list public void push(int new_data) { /* 1. allocate node * 2. put in the data */ Node new_Node = new Node(new_data); /* 3. Make next of new node as head and previous as NULL */ new_Node.next = head; new_Node.prev = null; /* 4. change prev of head node to new node */ if (head != null) head.prev = new_Node; /* 5. move the head to point to the new node */ head = new_Node; }
To Add After a Given Node use this method
/* Given a node as prev_node, insert a new node after the given node */ public void InsertAfter(Node prev_Node, int new_data) { /*1. check if the given prev_node is NULL */ if (prev_Node == null) { System.out.println("The given previous node cannot be NULL "); return; } /* 2. allocate node * 3. put in the data */ Node new_node = new Node(new_data); /* 4. Make next of new node as next of prev_node */ new_node.next = prev_Node.next; /* 5. Make the next of prev_node as new_node */ prev_Node.next = new_node; /* 6. Make prev_node as previous of new_node */ new_node.prev = prev_Node; /* 7. Change previous of new_node's next node */ if (new_node.next != null) new_node.next.prev = new_node; }
Hope This Helps.