JavaScript Program to Find N Largest Elements from a Linked List
Last Updated :
04 Mar, 2024
This JavaScript program is designed to identify the N largest elements from a linked list. A linked list is a linear data structure where elements, known as nodes, are connected via pointers.
The program iterates through the linked list to determine the N largest elements it contains.
Brute Force Approach
The idea is to sort the linked list using any sorting method and then traverse the list up to N. Sort the given list using bubble sort. Traverse the list up to N values. Print the values.
Example: The below example finds N largest elements from a linked list in JavaScript.
JavaScript
class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
function createLinkedList(arr) {
if (arr.length === 0) {
return null;
}
let head = new Node(arr[0]);
let current = head;
for (let i = 1; i < arr.length; i++) {
current.next = new Node(arr[i]);
current = current.next;
}
return head;
}
function bubbleSortLinkedList(head) {
if (!head || !head.next) {
return head;
}
let swapped;
do {
swapped = false;
let current = head;
let prev = null;
while (current.next) {
if (current.value <
current.next.value) {
let temp = current.next;
current.next = temp.next;
temp.next = current;
if (prev) {
prev.next = temp;
} else {
head = temp;
}
prev = temp;
swapped = true;
} else {
prev = current;
current = current.next;
}
}
} while (swapped);
return head;
}
function findNLargestElements(head, N) {
let sortedHead =
bubbleSortLinkedList(head);
let current = sortedHead;
let count = 0;
while (current && count < N) {
console.log(current.value);
current = current.next;
count++;
}
}
const linkedList =
createLinkedList([5, 3, 8, 1, 6, 2]);
const N = 3;
console.log(`Top ${N} largest elements:`);
findNLargestElements(linkedList, N);
OutputTop 3 largest elements:
8
6
5
Max Heap Approach
Store the elements of the linked list in a priority queue (max heap). Pop out the elements from the heap till N becomes 0 and add it to an array. Return the array as our answer.
Example: The below example find N largest elements from a linked list in JavaScript.
JavaScript
class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
function createLinkedList(arr) {
if (arr.length === 0) {
return null;
}
let head = new Node(arr[0]);
let current = head;
for (let i = 1; i < arr.length; i++) {
current.next = new Node(arr[i]);
current = current.next;
}
return head;
}
class MinHeap {
constructor() {
this.heap = [];
}
insert(value) {
this.heap.push(value);
this.heapifyUp(this.heap.length - 1);
}
heapifyUp(index) {
let parentIndex = Math.floor((index - 1) / 2);
while (parentIndex >= 0 &&
this.heap[parentIndex] >
this.heap[index]) {
[this.heap[parentIndex], this.heap[index]] =
[this.heap[index], this.heap[parentIndex]];
index = parentIndex;
parentIndex = Math.floor((index - 1) / 2);
}
}
extractMin() {
if (this.heap.length === 0)
return null;
if (this.heap.length === 1)
return this.heap.pop();
const minValue = this.heap[0];
this.heap[0] = this.heap.pop();
this.heapifyDown(0);
return minValue;
}
heapifyDown(index) {
let leftChildIndex = 2 * index + 1;
let rightChildIndex = 2 * index + 2;
let smallestIndex = index;
if (leftChildIndex < this.heap.length &&
this.heap[leftChildIndex] <
this.heap[smallestIndex]) {
smallestIndex = leftChildIndex;
}
if (rightChildIndex < this.heap.length &&
this.heap[rightChildIndex] <
this.heap[smallestIndex]) {
smallestIndex = rightChildIndex;
}
if (smallestIndex !== index) {
[this.heap[index], this.heap[smallestIndex]] =
[this.heap[smallestIndex], this.heap[index]];
this.heapifyDown(smallestIndex);
}
}
}
function findNLargestElements(head, N) {
const minHeap = new MinHeap();
let current = head;
while (current) {
minHeap.insert(current.value);
if (minHeap.heap.length > N) {
minHeap.extractMin();
}
current = current.next;
}
const result = [];
while (minHeap.heap.length > 0) {
result.unshift(minHeap.extractMin());
}
return result;
}
const linkedList =
createLinkedList([22, 555, 324, 1, 60, 2]);
const N = 3;
console.log(`Top ${N} largest elements:`);
const largestElements =
findNLargestElements(linkedList, N);
console.log(largestElements);
OutputTop 3 largest elements:
[ 555, 324, 60 ]
Similar Reads
JavaScript Program to Find Largest Number in a Linked List Finding the largest number in a linked list is a common problem and can be efficiently solved using both iterative and recursive approaches. A linked list is a fundamental data structure where each element, known as a node, is connected to the next one, forming a chain. Table of Content Iterative Ap
3 min read
find N largest elements from a Linked list Given a Linked list of integers, the task is to find N largest elements in the Linked List. Examples: Input: [4, 5, 1, 2, 9], N = 2Output: [9, 5] Input: [81, 52, 45, 10, 3, 2, 96], N = 3Output: [ 96, 81, 52] Method 1 : Brute ForceApproach: To solve the problem follow the below idea: The idea is to S
15+ min read
Second Largest Number in a linked list in JavaScript A linked list is a fundamental data structure where each element, known as a node, is connected to the next one, forming a chain. We are given a linked list and have to find the second-largest element in it. Table of Content Using iterationUsing RecursionUsing iterationIn this method, we traverse th
3 min read
Java Program to Return the Largest Element in a List Given a List, find the largest element in it. There are multiple approaches to tackle this problem, such as iterating through the List or using various inbuilt functions. Input : List = [5, 3, 234, 114, 154] Output : 234 Input : List = {10, 20, 4} Output : 20Approach 1: Using a ForEach Loop Create L
3 min read
JavaScript Program to Find Smallest Number in a Linked List Given a linked list, the task is to find the smallest number in a linked list in JavaScript. A "linked list" is a data structure to store data where each piece of information is connected to the next one, forming a chain. Each piece has its data and knows where to find the next piece. It's a basic b
3 min read
Java Program to Implement Triply Linked List Unlike arrays, linked list elements are not stored at a contiguous location; the elements are linked using pointers. In this post, methods to insert a new node in a linked list are discussed. A node can be inserted in three ways either at the front of the linked list or after a given node or at the
8 min read