Arranging Single Linked List in Alternate Odd and Even Nodes Order using JavaScript

Introduction

JavaScript is a programming language that focuses on object-oriented principles and is primarily utilized for enhancing web functionality. A particularly exciting feature of JavaScript is its ability to manipulate data structures, including linked lists. In this tutorial, we will explore the process of creating a singly linked list through a unique, unconventional, and certainly non-traditional approach using JavaScript. This algorithmic challenge necessitates a robust understanding of linked lists as well as the skills to effectively splice and manipulate nodes.

Linked List Overview

A linked list can be described as a data structure resembling a series of bumps, where each node references the subsequent node in the sequence. This singularly connected structure is noted for its straightforwardness and flexibility, rendering it an ideal choice for addressing this particular issue.

Problem Statement

In the context of a connected yet unanchored table, the objective is to organize its uneven elements so that every uniquely identified element is visible through the elements that are officially listed. For example, a linked sequence containing the elements 1-> 2-> 3-> 4-> 5 must be reordered to become 1-> 3-> 5-> 2-> 4.

Approach

In order to address this issue, we can adopt a methodical, step-by-step strategy utilizing JavaScript. Initially, we must segment the linked list and isolate the significant elements or distinct segments into individual lists. Furthermore, we will merge these lists according to the desired sequence.

JavaScript offers a powerful and intuitive environment for tackling algorithmic challenges, as well as handling data structures such as linked lists. In this tutorial, we examined a method to reorganize a singly linked list into a unique and somewhat intricate sequence. By grasping the fundamentals of linked lists and leveraging JavaScript's features, we were able to implement an efficient solution to this problem. You are encouraged to expand and modify this code for various linked list manipulation tasks or to explore more complex algorithms within the scope of JavaScript development.

Method 1 (Simple):

Within this framework, we generate two heaps: Odd and Indeed. We traverse the list, and upon discovering an Indeed knot positioned at an odd index, we place the address of this knot onto the Indeed Stack. Conversely, if we find an odd knot situated at an even index, we store the address of that knot onto the Odd Stack. After we have processed the entire list, we remove the elements from the top of both heaps and modify their data values. This process is reiterated until both heaps are completely depleted.

Step 1:

Create two separate heaps named Odd and Indeed. These heaps will hold pointers that reference the bumps within the list.

Step 2:

Navigate through the list starting from the launch point to the conclusion while utilizing the variable current. Carry out the subsequent actions repeatedly.

Step 3:

In the event that the existing knot is confirmed to be present and is located in an unusual position, then proceed to add the address of this knot to the mound.

Step 4:

In the event that the existing knot is odd and it is located at an even index, transfer the address of this knot to Mound Odd.

(END OF TRAVERSAL).

Step 5:

The dimensions of both heaps will remain identical. As long as neither of the heaps is empty, swap the peak elements of the two. Subsequently, perform a pop operation on both heaps to remove the respective top elements.

Step 6:

The list is now rearranged.

Implementation:

Example

<script> 
// Javascript program to rearrange nodes as alternate odd even nodes in a Singly Linked List class node 
class Node 
{ constructor () 
{ 
this.data = 0; 
this.next = null; 
} 
} 
// A utility function to print 
// linked list 
function print list(node) 
{ 
while (node != null) 
{ 
document.write(node.data + " "); 
node = node. next; 
} 
document.write(); 
} 
//Function to create newNode 
// in a linked list 
function newNode(key) 
{ 
var temp = new Node(); 
temp.data = key; 
temp.next = null; 
return temp; 
} 
//Function to insert at the beginning 
function inserting(head, val) 
{ 
var temp = newNode(val); 
temp.next = head; 
head = temp; 
return head; 
} 
//Function to rearrange the 
// odd and even nodes 
function rearrangeOddEven(head) 
{ 
var odd = []; 
var even = []; 
var i = 1; 
while (head != null) 
{ 
if (head.data % 2 != 0 && 
i % 2 == 0) 
{ 
// Odd Value in Even Position 
// Add a pointer to the current node 
// in odd stack 
odd.push(head); 
} 
else if (head.data % 2 == 0 && 
i % 2 != 0) 
{ 
// Even Value in Odd Position 
// Add a pointer to the current node 
// in even stack 
even.push(head); 
} 
head = head.next; 
i++; 
} 
while (odd.length > 0 && 
even. length > 0) 
{ 
// Swap Data at the top of 
// two stacks 
var k = odd[odd.length - 1].data; 
odd[odd.length - 1].data = even[even.length - 1].data; 
even[even.length - 1].data = k; 
odd.pop(); 
even.pop(); 
}} 
// Driver code 
var head = newNode(8); 
head = insertBeg(head, 7); 
head = insertBeg(head, 6); 
head = insertBeg(head, 5); 
head = insertBeg(head, 3); 
head = insertBeg(head, 2); 
head = insertBeg(head, 1); 
document.write("Linked List:<br/>"); 
printList(head); 
rearrangeOddEven(head); 
document.write("<br/>Linked List after " + 
"Rearranging:<br/>"); 
printList(head); 
// This code is contributed by aashish1995 
</script>

Output

The output of the above code is:

Explanation:

The specified JavaScript regulation delineates a linked list and incorporates a method to sort its nodes according to their positions and values. This linked list is depicted through a node structure, where each node contains a data field and a pointer that references the subsequent node. The head pointer directs to the initial elements of the linked list.

The newly introduced node feature generates an entirely new node that possesses a unique and significant value. The insertion function is responsible for adding this new node at the beginning of the associated list.

The primary logic resides within the reorganized Odd Even property, which traverses the associated list, placing odd values in even-indexed positions and even values in odd-indexed positions into distinct heaps (odd and even). Furthermore, it swaps the values of corresponding elements from both heaps.

The law of motive force generates a corresponding table and displays it in advance after reorganizing the exceptional and properly positioned elements. This reorganization is accomplished through the utilization of value swapping prior to a modified linked list.

Method 2 (Efficient)

  • Insulate peculiar and, indeed, valuable values within the table. After this, all odd values will arise inclusively, followed by all indeed values.
  • Split the list into lists that are atypical or indeed.
  • Combine the Indeed listing with the crazy list.
  • REARRANGE( HEAD)
  1. Step 1:

Traverse the table using NODE TEMP.

If TEMP is odd

Add TEMP to the morning of the list.

END OF IF)

(END OF TRAVERSAL)

Step 2:

Set TEMP to alternate details of the list.

Step 3:

Set PREV_TEMP to the first element of the list.

Step 4:

The execution of the TEMP knot operation is exceptional.

the knot is yet to be encountered.

= TEMP, TEMP = TEMP- > NEXT

(END OF TRAVERSAL)

Step 5:

Set Indeed to TEMP. SetPREV_TEMP- > NEXT to NULL

Step 6:

I = HEAD, J = Indeed

Step 7:

Repetition while I! = NULL and J! = NULL

Store the posterior bumps of I and J in K and L.

K = I- > NEXT, L = J- > NEXT

I- > NEXT = J, J- > NEXT = K, PTR = J

I = K, and J = L.

(END OF THE CIRCLE)

Step 8:

If I == NULL

PTR > NEXT = J

END of IF)

Return Head.

Step 9:

Code:

Example

// JavaScript program to rearrange nodes  
// as alternate odd even nodes in  
// a Singly Linked List  
// Structure node 
class Node  
{ 
    constructor()  
    { 
        this.data = 0; 
        this.next = null; 
    } 
} 
// A utility function to print 
// linked list 
function printList(node)  
{ 
    while (node != null)  
    { 
        document.write(node.data + " "); 
        node = node. next; 
    } 
    document.write("<br/>"); 
} 
//Function to create newNode 
// in a linked list 
function newNode(key)  
{ 
    var temp = new Node(); 
    temp.data = key; 
    temp.next = null; 
    return temp; 
} 
//Function to insert at the beginning 
function insertBeg(head, val)  
{ 
    var temp = newNode(val); 
    temp.next = head; 
    head = temp; 
    return head; 
} 
//Function to rearrange the 
// odd and even nodes 
function rearrange(head)  
{ 
    // Step 1: Segregate even and odd nodes 
    // Step 2: Split odd and even lists 
    // Step 3: Merge an even list into an odd list 
    var even; 
    var temp, prev_temp; 
    var i, j, k, l, ptr = null; 
    // Step 1: Segregate Odd and   
    // Even Nodes 
    temp = (head). next; 
    prev_temp = head; 
    while (temp != null)  
    { 
        // Backup next pointer of temp 
        var x = temp.next; 
        // If the temp is odd, move the node 
        // to the beginning of the list 
        if (temp. data % 2 != 0)  
        { 
            prev_temp.next = x; 
            temp.next = (head); 
            (head) = temp; 
        } 
        else 
        { 
            prev_temp = temp; 
        } 
        // Advance Temp Pointer 
        temp = x; 
    } 
    // Step 2 
    // Split the List into Odd and even 
    temp = (head).next; 
    prev_temp = (head); 
    while (temp != null &&  
           temp.data % 2 != 0)  
    { 
        prev_temp = temp; 
        temp = temp. next; 
    } 
    even = temp; 
    // End the odd List (Make last  
    // node null) 
    prev_temp.next = null; 
    // Step 3: 
    // Merge Even List into odd 
    i = head; 
    j = even; 
    while (j != null &&  
           i != null)  
    { 
        // While both lists are not 
        // exhausted Backup next 
        // pointers of i and j 
        k = i.next; 
        l = j.next; 
        i.next = j; 
        j.next = k; 
        // ptr points to the latest  
        // node added 
        ptr = j; 
        // Advance i and j pointers 
        i = k; 
        j = l; 
    } 
    if (i == null)  
    { 
        // Odd list exhausts before even, 
        // append remainder of even list 
        // to odd. 
        ptr.next = j; 
    } 
    // The case where even list exhausts  
    // before the odd list is automatically  
    // handled since we merge the event  
    // list into the odd list 
    return head; 
} 
// Driver Code 
var head = newNode(8); 
head = insertBeg(head, 7); 
head = insertBeg(head, 6); 
head = insertBeg(head, 3); 
head = insertBeg(head, 5); 
head = insertBeg(head, 1); 
head = insertBeg(head, 2); 
head = insertBeg(head, 10); 
document.write("Linked List:<br/>"); 
printList(head); 
document.write("Rearranged List<br/>"); 
head = rearrange(head); 
printList(head);

Output

The output of the above code is:

Explanation:

The provided JavaScript code illustrates the process of reorganizing a separately linked table by partitioning its elements into odd or even groups, detaching them, and subsequently merging the even elements back into the odd elements.

The Node class outlines the structure of a connected table knot, which includes a record subject alongside a pointer to the next node. The printList function is a utility designed to display the fundamental elements of the linked list.

The newly introduced Node function generates a new node containing a specified key price and adds this node to the front of the linked list.

The property of rearrangement is essential to the process of rearranging. Initially, it identifies and separates odd or unique elements by moving these distinctive elements to the front. Additionally, it categorizes the dataset into common and unique variables. Ultimately, it combines the unique list with the common list.

The motive force law establishes a linked table, outputs it, executes the rearrangement function of the rearrange point, and subsequently displays the updated list. This rearrangement ensures that unusual and pertinent elements are interspersed in an alternating pattern within the final linked table.

Conclusion:

Ultimately, the execution of a JavaScript function to sort a disjoint linked list into a specified order, particularly for handling unusual or irregular elements, demonstrates the language's adaptability and capability in tackling algorithmically intensive tasks. The implemented method utilizes the fundamental structure of linked lists to effectively isolate these atypical or irregular elements before merging them into the desired sequence.

This issue underscores the importance of a robust framework of data structures, particularly linked lists, along with the ability to effectively manage and manipulate irregularities. The modular and object-oriented characteristics of JavaScript, as defined by its principles, enhance the comprehensibility of the solution.

As developers, adapting and integrating this principle for similar liabilities or investigating more advanced algorithms will become feasible, demonstrating the capabilities of JavaScript in tackling a wide array of programming issues. In summary, this tutorial not only tackles a specific problem related to rearranging linked lists but also acts as a practical example of algorithmic challenges within the context of JavaScript.

Input Required

This code uses input(). Please provide values below: