Remove last node of the linked list in typescript


Ts program for Remove last node of the linked list. Here more solutions.
/*
TypeScript program for
Delete the last node of singly 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;
public tail: LinkNode;
constructor()
{
this.head = null;
this.tail = null;
}
// Add new node at the end of linked list
public addNode(value: number)
{
// Create a new node
var node = new LinkNode(value);
if (this.head == null)
{
this.head = node;
}
else
{
this.tail.next = node;
}
this.tail = node;
}
// Display linked list element
public display()
{
if (this.head == null)
{
console.log("Empty Linked List");
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");
}
// Delete last node of singly linked list
public deleteLastNode()
{
if (this.head == null)
{
console.log("Empty Linked List");
return;
}
else
{
var temp = this.head;
var find: LinkNode = null;
// Find second last node
while (temp.next != null)
{
find = temp;
temp = temp.next;
}
if (find == null)
{
// Delete head node of linked list
this.head = null;
this.tail = null;
}
else
{
// Set new last node
this.tail = find;
find.next = null;
}
}
}
public static main()
{
var sll = new SingleLL();
// Linked list
// 1 → 2 → 3 → 4 → 5 → 6 → NULL
sll.addNode(1);
sll.addNode(2);
sll.addNode(3);
sll.addNode(4);
sll.addNode(5);
sll.addNode(6);
console.log("Before Delete ");
sll.display();
sll.deleteLastNode();
console.log("After Delete ");
sll.display();
}
}
SingleLL.main();
/*
file : code.ts
tsc --target es6 code.ts
node code.js
*/
Output
Before Delete
1 →
2 →
3 →
4 →
5 →
6 →
NULL
After Delete
1 →
2 →
3 →
4 →
5 →
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