I'm making a method to add a Node into a list called "public void add(int index, T value)".
This method will put a value into an index, and then will have pointers to the next and previous elements in the list. I have messed up on the pointers to the previous nodes, which I have been sitting and experimenting but don't get to make it work.
Example: We have a list with Integer values [2, 4, 6] Instance variables: Node head, tail; int amount, changes;
Instance variables for the inner class are: T value; Node prev, next;
Input:
add(1, 3);
System.out.println(list.toString());
System.out.println(list.backwardsString());
Expected output:
[2, 3, 4, 6]
[6, 4, 3, 2]
My code so far:
public void add(int index, T value) {
if (index < 0 || index > amount) {
throw new IndexOutOfBoundsException("Index is not between 0 and amount!");
}
if (value== null) {
throw new NullPointerException("Value can't be null!");
}
if (amount == 0) {
head = tail= new Node<>(value, null, null);
}
else if (index == 0) {
head = head.prev= new Node<>(value, null, head);
}
else if (index == amount) {
tail = tail.next= new Node<>(value, tail, null);
}
else {
Node<T> p = head;
for (int i = 1; i < index; i++) {
p = p.next;
}
p.next= new Node<>(value, p, p.next);
p = tail;
for (int i = amount; i > index; i--) {
p.prev= new Node<>(value, p.prev, p);
p = p.prev;
}*/
}
amount++;
changes++;
}
In this occasion I would also ask how does
p.prev.next or p.next.prev
work?