Sorted order insertion in doubly linked list in typescript
Ts program for Sorted order insertion in doubly linked list. Here problem description and explanation.
// TypeScript Program For
// Insert node in sorted order
// Define class of linked list Node
class LinkNode
{
public data: number;
public next: LinkNode;
public prev: LinkNode;
constructor(data: number)
{
this.data = data;
this.next = null;
this.prev = null;
}
}
class DoublyLinkedList
{
public head: LinkNode;
constructor()
{
// Set inital value
this.head = null;
}
// Insert Node at sorted way
public insert(value: number)
{
// Create a dynamic node
var node = new LinkNode(value);
if (this.head == null)
{
// Add first node
this.head = node;
}
else if (this.head.data >= node.data)
{
// When need to add node at begining position
this.head.prev = node;
node.next = this.head;
this.head = node;
}
else
{
var current = this.head;
// Find position to add new node
while (current != null &&
current.next != null &&
current.next.data <= value)
{
current = current.next;
}
// Insert new node between the nodes
node.next = current.next;
if (current.next != null)
{
// When next node exists
current.next.prev = node;
}
node.prev = current;
current.next = node;
}
}
// Display node element of doubly linked list
public display()
{
if (this.head == null)
{
console.log("Empty Linked List");
}
else
{
console.log("Linked List Head to Tail :");
// Get first node of linked list
var temp = this.head;
var last: LinkNode = null;
// iterate linked list
while (temp != null)
{
// Display node value
console.log(" " + temp.data);
last = temp;
// Visit to next node
temp = temp.next;
}
console.log("\nLinked List Tail to Head :");
// Get last node of linked list
temp = last;
// iterate linked list
while (temp != null)
{
// Display node value
console.log(" " + temp.data);
// Visit to prev node
temp = temp.prev;
}
}
}
public static main(args: string[])
{
var dll = new DoublyLinkedList();
// Insert following linked list nodes
dll.insert(5);
dll.insert(3);
dll.insert(11);
dll.insert(4);
dll.insert(6);
dll.insert(1);
dll.insert(8);
dll.insert(12);
dll.display();
}
}
DoublyLinkedList.main([]);
/*
file : code.ts
tsc --target es6 code.ts
node code.js
*/
Output
Linked List Head to Tail :
1
3
4
5
6
8
11
12
Linked List Tail to Head :
12
11
8
6
5
4
3
1
Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.
New Comment