The method not working:
public void insert_before_node(Node givenNode, int data) {
Node newNode = new Node(data);
newNode.prev = givenNode.prev;
givenNode.prev = newNode;
newNode.next = givenNode;
if(newNode.prev != null)
newNode.prev.next = newNode;
}
Another add method which is working:
public void insert_front(int data) {
Node newNode = new Node(data);
newNode.next = head;
newNode.prev = null;
if(head != null)
head.prev = newNode;
head = newNode;
}
A print method to debug:
public void print() {
Node n = head;
while(n != null){
System.out.println(n.data);
n = n.next;
}
}
DoublyLinkedList class:
public class DoublyLinkedList {
static class Node {
int data;
Node next;
Node prev;
Node(int data) {
this.data = data;
this.next = null;
this.prev = null;
}
}
Node head;
DoublyLinkedList() {
this.head = null;
}
public static void main(String[] args) {
DoublyLinkedList ll = new DoublyLinkedList();
ll.insert_front(0);
ll.insert_before_node(ll.head, 100);
ll.print();
}
}
LinkedList and Node implementations are very straightforward. Find here: https://www.geeksforgeeks.org/doubly-linked-list/
I first create a linkedlist, insert_front() a value to make the head not null, then use the method above to insert something else. Insertion to front, end, after a node are working, however, this insert_before_node() is not working. What I have inserted with this method is not appears on my print.
I draw on a paper too, still couldn't find the problem.
The geeksforgeeks link also has no java implementation for this method.
insert_front()is working? How does the caller know about the new head of the list?insert_frontis useless (head = newNode;) This method should return the new head, otherwise how do you keep track of the new head? You should show us your test code.