I am trying to add few nodes in a sorted doubly linked list. There is something wrong with the code which I am not able to figure out . I created two nodes current and prev which will help in traversing.
/*
Insert Node at the end of a linked list
head pointer input could be NULL as well for empty list
Node is defined as
class Node {
int data;
Node next;
Node prev;
}
*/
Node sortedInsert(Node head, int data) {
Node newnode = new Node();
newnode.data = data;
Node current = head;
Node pre = null;
if(head == null) {
head = newnode;
newnode.prev = null;
}
else if (head.data >= newnode.data) {
newnode.next = head;
head.prev = newnode;
head = newnode;
return newnode;
}
while(current!=null && current.data <= newnode.data) {
pre = current;
current = current.next;
newnode.prev = pre;
pre.next = newnode;
newnode.next = current;
if (current != null) {
current.prev = newnode;
}
}
return head;
}