## Algorithm

Problem Name: Data Structures - Inserting a Node Into a Sorted Doubly Linked List

In this HackerRank in Data Structures - Inserting a Node Into a Sorted Doubly Linked List solutions

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 at the proper location to maintain the sort.

Example

head refers to the list 1 -> 2 -> 4 -> NULL

data = 3

Return a reference to the new list: 1 -> 2 -> 3 -> 4 -> NULL

## Code Examples

### #1 Code Example with C Programming

```Code - C Programming```

``````
#include <assert.h>
#include <limits.h>
#include <math.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int data;
};

};

node->data = node_data;
node->next = NULL;
node->prev = NULL;

return node;
}

} else {
}

}

void print_doubly_linked_list(DoublyLinkedListNode* node, char* sep, FILE* fptr) {
while (node) {
fprintf(fptr, "%d", node->data);

node = node->next;

if (node) {
fprintf(fptr, "%s", sep);
}
}
}

while (node) {
DoublyLinkedListNode* temp = node;
node = node->next;

free(temp);
}
}

/*
* Complete the 'sortedInsert' function below.
*
* The function is expected to return an INTEGER_DOUBLY_LINKED_LIST.
* The function accepts following parameters:
*  1. INTEGER_DOUBLY_LINKED_LIST llist
*  2. INTEGER data
*/

/*
* For your reference:
*
*     int data;
* };
*
*/

if (head == NULL) return new;
if (new->data  < = head->data) { // Insert at head of list
return new;
}

while (curr->next != NULL && curr->next->data  <  new->data) {
curr = curr->next;
}

if (curr->next == NULL) { // Insert at end of list
curr->next = new;
new->prev = curr;
} else { // Insert somewhere in the middle
new->next = curr->next;
curr->next->prev = curr;
curr->next = new;
}

}

int main()
{
FILE* fptr = fopen(getenv("OUTPUT_PATH"), "w");

char* t_endptr;
char* t_str = readline();
int t = strtol(t_str, &t_endptr, 10);

if (t_endptr == t_str || *t_endptr != '\0') { exit(EXIT_FAILURE); }

for (int t_itr = 0; t_itr  <  t; t_itr++) {
llist->tail = NULL;

char* llist_count_endptr;
char* llist_count_str = readline();
int llist_count = strtol(llist_count_str, &llist_count_endptr, 10);

if (llist_count_endptr == llist_count_str || *llist_count_endptr != '\0') { exit(EXIT_FAILURE); }

for (int i = 0; i  <  llist_count; i++) {
char* llist_item_endptr;
char* llist_item_str = readline();
int llist_item = strtol(llist_item_str, &llist_item_endptr, 10);

if (llist_item_endptr == llist_item_str || *llist_item_endptr != '\0') { exit(EXIT_FAILURE); }

}

char* data_endptr;
char* data_str = readline();
int data = strtol(data_str, &data_endptr, 10);

if (data_endptr == data_str || *data_endptr != '\0') { exit(EXIT_FAILURE); }

char *sep = " ";

fprintf(fptr, "\n");

}

fclose(fptr);

return 0;
}

size_t alloc_length = 1024;
size_t data_length = 0;
char* data = malloc(alloc_length);

while (true) {
char* cursor = data + data_length;
char* line = fgets(cursor, alloc_length - data_length, stdin);

if (!line) { break; }

data_length += strlen(cursor);

if (data_length  <  alloc_length - 1 || data[data_length - 1] == '\n') { break; }

size_t new_length = alloc_length << 1;
data = realloc(data, new_length);

if (!data) { break; }

alloc_length = new_length;
}

if (data[data_length - 1] == '\n') {
data[data_length - 1] = '\0';
}

data = realloc(data, data_length);

return data;
}

``````
Copy The Code &

### #2 Code Example with C++ Programming

```Code - C++ Programming```

``````
#include <bits/stdc++.h>

using namespace std;

public:
int data;

this->data = node_data;
this->next = nullptr;
this->prev = nullptr;
}
};

public:

this->tail = nullptr;
}

void insert_node(int node_data) {

} else {
this->tail->next = node;
node->prev = this->tail;
}

this->tail = node;
}
};

void print_doubly_linked_list(DoublyLinkedListNode* node, string sep, ofstream& fout) {
while (node) {
fout << node->data;

node = node->next;

if (node) {
fout << sep;
}
}
}

while (node) {
DoublyLinkedListNode* temp = node;
node = node->next;

free(temp);
}
}

// Complete the sortedInsert function below.

/*
* For your reference:
*
*     int data;
* };
*
*/

node->data = data;
node->next = node->prev = NULL;

return node;

return node;
}

}

int main()
{
ofstream fout(getenv("OUTPUT_PATH"));

int t;
cin >> t;
cin.ignore(numeric_limits < streamsize>::max(), '\n');

for (int t_itr = 0; t_itr  <  t; t_itr++) {

int llist_count;
cin >> llist_count;
cin.ignore(numeric_limits < streamsize>::max(), '\n');

for (int i = 0; i  <  llist_count; i++) {
int llist_item;
cin >> llist_item;
cin.ignore(numeric_limits < streamsize>::max(), '\n');

llist->insert_node(llist_item);
}

int data;
cin >> data;
cin.ignore(numeric_limits < streamsize>::max(), '\n');

print_doubly_linked_list(llist1, " ", fout);
fout << "\n";

}

fout.close();

return 0;
}
``````
Copy The Code &

### #3 Code Example with Java Programming

```Code - Java Programming```

``````
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;

public class Solution {

static class DoublyLinkedListNode {
public int data;

public DoublyLinkedListNode(int nodeData) {
this.data = nodeData;
this.next = null;
this.prev = null;
}
}

static class DoublyLinkedList {

this.tail = null;
}

public void insertNode(int nodeData) {

if (this.head == null) {
} else {
this.tail.next = node;
node.prev = this.tail;
}

this.tail = node;
}
}

public static void printDoublyLinkedList(DoublyLinkedListNode node, String sep, BufferedWriter bufferedWriter) throws IOException {
while (node != null) {
bufferedWriter.write(String.valueOf(node.data));

node = node.next;

if (node != null) {
bufferedWriter.write(sep);
}
}
}

// Complete the sortedInsert function below.

/*
* For your reference:
*
*     int data;
* }
*
*/
if (head == null) {
return node;
} else if (data  < = head.data) {
return node;
} else {
}
}

private static final Scanner scanner = new Scanner(System.in);

public static void main(String[] args) throws IOException {
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));

int t = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

for (int tItr = 0; tItr  <  t; tItr++) {

int llistCount = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

for (int i = 0; i  <  llistCount; i++) {
int llistItem = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

llist.insertNode(llistItem);
}

int data = scanner.nextInt();
scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

printDoublyLinkedList(llist1, " ", bufferedWriter);
bufferedWriter.newLine();
}

bufferedWriter.close();

scanner.close();
}
}
``````
Copy The Code &

### #4 Code Example with Javascript Programming

```Code - Javascript Programming```

``````
'use strict';

const fs = require('fs');

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
inputString += inputStdin;
});

process.stdin.on('end', _ => {
inputString = inputString.replace(/\s*\$/, '')
.split('\n')
.map(str => str.replace(/\s*\$/, ''));

main();
});

return inputString[currentLine++];
}

const DoublyLinkedListNode = class {
constructor(nodeData) {
this.data = nodeData;
this.next = null;
this.prev = null;
}
};

const DoublyLinkedList = class {
constructor() {
this.tail = null;
}

insertNode(nodeData) {
let node = new DoublyLinkedListNode(nodeData);

if (this.head == null) {
} else {
this.tail.next = node;
node.prev = this.tail;
}

this.tail = node;
}
};

function printDoublyLinkedList(node, sep, ws) {
while (node != null) {
ws.write(String(node.data));

node = node.next;

if (node != null) {
ws.write(sep);
}
}
}

/*
* Complete the 'sortedInsert' function below.
*
* The function is expected to return an INTEGER_DOUBLY_LINKED_LIST.
* The function accepts following parameters:
*  1. INTEGER_DOUBLY_LINKED_LIST llist
*  2. INTEGER data
*/

/*
* For your reference:
*
*     int data;
* }
*
*/

function sortedInsert(head, data) {
if(head == null) {
}
var current = head;
if(data < current.data) {
var newNode = new DoublyLinkedListNode(data);
newNode.next = current;
current.prev = newNode;
return newNode;
}

while(current != null> {
if(data >= current.data) {
if(current.next == null) {
var newNode = new DoublyLinkedListNode(data);
current.next = newNode;
newNode.prev = current;

}

if(current.next.data >= data) {
var newNode = new DoublyLinkedListNode(data);
newNode.next = current.next;
newNode.prev = current;
current.next = newNode;
newNode.next.prev = newNode;

}
}

current = current.next;
}

}

function main() {
const ws = fs.createWriteStream(process.env.OUTPUT_PATH);

const t = parseInt(readLine(), 10);

for (let tItr = 0; tItr < t; tItr++) {
const llistCount = parseInt(readLine(), 10);

let llist = new DoublyLinkedList();

for (let i = 0; i  <  llistCount; i++) {
const llistItem = parseInt(readLine(), 10);
llist.insertNode(llistItem);
}

const data = parseInt(readLine(), 10);

let llist1 = sortedInsert(llist.head, data);

printDoublyLinkedList(llist1, " ", ws)
ws.write("\n");
}

ws.end(>;
}
``````
Copy The Code &

### #5 Code Example with Python Programming

```Code - Python Programming```

``````
#!/bin/python3

import math
import os
import random
import re
import sys

def __init__(self, node_data):
self.data = node_data
self.next = None
self.prev = None

def __init__(self):
self.tail = None

def insert_node(self, node_data):

else:
self.tail.next = node
node.prev = self.tail

self.tail = node

def print_doubly_linked_list(node, sep, fptr):
while node:
fptr.write(str(node.data))

node = node.next

if node:
fptr.write(sep)

#
# Complete the 'sortedInsert' function below.
#
# The function is expected to return an INTEGER_DOUBLY_LINKED_LIST.
# The function accepts following parameters:
#  1. INTEGER_DOUBLY_LINKED_LIST llist
#  2. INTEGER data
#

#
# For your reference:
#
#     int data
#
#

if cur.data > data or cur.data == data:
node.next = cur
cur.prev = node
while cur.next:
if (cur.data < data and cur.next.data > data) or cur.data == data:
node.next = cur.next
cur.next.prev = node
node.prev = cur
cur.next = node
cur = cur.next
if cur.data < data or cur.data == data:
node.prev = cur
cur.next = node

if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')

t = int(input())

for t_itr in range(t):
llist_count = int(input())

for _ in range(llist_count):
llist_item = int(input())
llist.insert_node(llist_item)

data = int(input())

llist1 = sortedInsert(llist.head, data)

print_doubly_linked_list(llist1, ' ', fptr)
fptr.write('\n')

fptr.close()
``````
Copy The Code &