I've decided to do a simple linked list question to brush up my Java & CS.
This is the solution for
Given a reference to the head of a doubly-linked list and an integer, \$data\$ , create a new DoublyLinkedListNode object having data value \$data\$ and insert it into a sorted linked list while maintaining the sort. Full question
/*
* For your reference:
*
* DoublyLinkedListNode {
* int data;
* DoublyLinkedListNode next;
* DoublyLinkedListNode prev;
* }
*
*/
static DoublyLinkedListNode sortedInsert(DoublyLinkedListNode head, int data) {
DoublyLinkedListNode nodeToInsert = new DoublyLinkedListNode(data);
if (head == null) return nodeToInsert;
DoublyLinkedListNode current = head;
while (current != null) {
if (data < current.data && current.prev == null) {
current.prev = nodeToInsert;
nodeToInsert.next = current;
return nodeToInsert;
}
if (data >= current.data && current.next == null) {
current.next = nodeToInsert;
nodeToInsert.prev = current;
break;
}
if (data >= current.data && data <= current.next.data) {
DoublyLinkedListNode temp = current.next;
current.next = nodeToInsert;
nodeToInsert.prev = current;
temp.prev = nodeToInsert;
nodeToInsert.next = temp;
break;
}
current = current.next;
}
return head;
}
This passes all test cases.