Insert node at beginning of linked list in typescript

Ts program for Insert node at beginning of linked list. Here more solutions.
/*
TypeScript program for
Insert node at beginning of linked list
*/
// Linked list node
class LinkNode
{
public data: number;
public next: LinkNode;
constructor(data: number)
{
this.data = data;
this.next = null;
}
}
class SingleLL
{
public head: LinkNode;
constructor()
{
this.head = null;
}
// Adding new node at beginning of linked list
public addNode(data: number)
{
// Create new node
var node = new LinkNode(data);
// Connect current node to previous head
node.next = this.head;
this.head = node;
}
// Display linked list element
public display()
{
if (this.head == null)
{
return;
}
var temp = this.head;
// iterating linked list elements
while (temp != null)
{
console.log(" " + temp.data );
// Visit to next node
temp = temp.next;
}
console.log(" NULL");
}
}
var sll = new SingleLL();
// Linked list
// 1 → 2 → 3 → 4 → 5 → 6 → 7 → 8 → NULL
sll.addNode(8);
sll.addNode(7);
sll.addNode(6);
sll.addNode(5);
sll.addNode(4);
sll.addNode(3);
sll.addNode(2);
sll.addNode(1);
sll.display();
/*
file : code.ts
tsc --target es6 code.ts
node code.js
*/
Output
1
2
3
4
5
6
7
8
NULL
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