Open In App

Javascript Program For Arranging Single Linked List In Alternate Odd and Even Nodes Order

Last Updated : 18 Jan, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given a singly linked list, rearrange the list so that even and odd nodes are alternate in the list.
There are two possible forms of this rearrangement. If the first data is odd, then the second node must be even. The third node must be odd and so on. Notice that another arrangement is possible where the first node is even, second odd, third even and so on. 
Examples:

Input: 11 -> 20 -> 40 -> 55 -> 77 -> 80 -> NULL
Output: 11 -> 20 -> 55 -> 40 -> 77 -> 80 -> NULL
20, 40, 80 occur in even positions and 11, 55, 77
occur in odd positions.

Input: 10 -> 1 -> 2 -> 3 -> 5 -> 6 -> 7 -> 8 -> NULL
Output: 1 -> 10 -> 3 -> 2 -> 5 -> 6 -> 7 -> 8 -> NULL
1, 3, 5, 7 occur in odd positions and 10, 2, 6, 8 occur
at even positions in the list

Method 1 (Simple): 
In this method, we create two stacks-Odd and Even. We traverse the list and when we encounter an even node in an odd position we push this node’s address onto Even Stack. If we encounter an odd node in an even position we push this node’s address onto Odd Stack. 
After traversing the list, we simply pop the nodes at the top of the two stacks and exchange their data. We keep repeating this step until the stacks become empty.

Step 1: Create two stacks Odd and Even.  
        These stacks will store the pointers to the nodes in the list 
Step 2: Traverse list from start to end, using the variable current. 
        Repeat following steps 3-4.
Step 3: If the current node is even and it occurs at an odd position, 
        push this node's address to stack Even.
Step 4: If the current node is odd and it occurs at an even position, 
        push this node's address to stack Odd. 
[END OF TRAVERSAL]. Step 5: The size of both the stacks will be the same. While both the stacks are not empty exchange the nodes at the top of the two stacks and pop both nodes from their respective stacks.  Step 6: The List is now rearranged. STOP

Javascript




<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 printList(node) 
{
    while (node != null
    {
        document.write(node.data + " ");
        node = node.next;
    }
    document.write();
}
  
// Function to create newNode
// in a linkedlist
function newNode(key) 
{
    var temp = new Node();
    temp.data = key;
    temp.next = null;
    return temp;
}
  
// Function to insert at 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 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 pointer to current node
            // in odd stack
            odd.push(head);
        }
  
        else if (head.data % 2 == 0 && 
                 i % 2 != 0) 
        {
            // Even Value in Odd Position
            // Add pointer to 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:

Linked List:
1 2 3 5 6 7 8 
Linked List after Rearranging:
1 2 3 6 5 8 7

Time Complexity : O(n) 
Auxiliary Space : O(n)

Method 2 (Efficient)

  1. Segregate odd and even values in the list. After this, all odd values will occur together followed by all even values. 
  2. Split the list into two lists odd and even.
  3. Merge the even list into odd list
REARRANGE (HEAD)
Step 1: Traverse the list using NODE TEMP. 
           If TEMP is odd
               Add TEMP to the beginning of the List
           [END OF IF]
        [END OF TRAVERSAL]
Step 2: Set TEMP to 2nd element of LIST.
Step 3: Set PREV_TEMP to 1st element of List
Step 4: Traverse using node TEMP as long as an even
        node is not encountered.
            PREV_TEMP = TEMP, TEMP = TEMP->NEXT
        [END OF TRAVERSAL]
Step 5: Set EVEN to TEMP. Set PREV_TEMP->NEXT to NULL
Step 6: I = HEAD, J = EVEN
Step 7: Repeat while I != NULL and J != NULL
            Store next nodes 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 LOOP]
Step 8: if I == NULL 
            PTR->NEXT = J
        [END of IF]
Step 8: Return HEAD.
Step 9: End

Javascript




<script>
// 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 linkedlist
function newNode(key) 
{
    var temp = new Node();
    temp.data = key;
    temp.next = null;
    return temp;
}
  
// Function to insert at 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 even list into 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 temp is odd move the node
        // to beginning of 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 odd list is automatically 
    // handled since we merge the even 
    // 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);
// This code is contributed by umadevi9616
</script>


Output:

Linked List:
10 2 1 5 3 6 7 8 
Rearranged List
7 10 3 2 5 6 1 8

Time Complexity : O(n) 
Auxiliary Space : O(1)

Please refer complete article on Alternate Odd and Even Nodes in a Singly Linked List for more details!



Previous Article
Next Article

Similar Reads

C++ Program For Arranging Single Linked List In Alternate Odd and Even Nodes Order
Given a singly linked list, rearrange the list so that even and odd nodes are alternate in the list.There are two possible forms of this rearrangement. If the first data is odd, then the second node must be even. The third node must be odd and so on. Notice that another arrangement is possible where the first node is even, second odd, third even an
8 min read
Java Program For Arranging Single Linked List In Alternate Odd and Even Nodes Order
Given a singly linked list, rearrange the list so that even and odd nodes are alternate in the list.There are two possible forms of this rearrangement. If the first data is odd, then the second node must be even. The third node must be odd and so on. Notice that another arrangement is possible where the first node is even, second odd, third even an
8 min read
Python Program For Arranging Single Linked List In Alternate Odd and Even Nodes Order
Given a singly linked list, rearrange the list so that even and odd nodes are alternate in the list.There are two possible forms of this rearrangement. If the first data is odd, then the second node must be even. The third node must be odd and so on. Notice that another arrangement is possible where the first node is even, second odd, third even an
7 min read
Alternate Odd and Even Nodes in a Singly Linked List
Given a singly linked list, rearrange the list so that even and odd nodes are alternate in the list.There are two possible forms of this rearrangement. If the first data is odd, then the second node must be even. The third node must be odd and so on. Notice that another arrangement is possible where the first node is even, second odd, third even an
23 min read
Append odd position nodes in reverse at the end of even positioned nodes in a Linked List
Given a linked list. The task is to segregate its even and odd position nodes in such a way that odd position nodes appear before even positioned nodes all the even positioned nodes must be in reverse order. Examples: Input: 1 -&gt; 2 -&gt; 3 -&gt; 4 -&gt; 5 -&gt; 6 -&gt; NULL Output : 1 -&gt; 3 -&gt; 5 -&gt; 6 -&gt; 4 -&gt; 2 -&gt; NULL Input : 1
11 min read
Javascript Program For Rearranging A Linked List Such That All Even And Odd Positioned Nodes Are Together
Rearrange a linked list in such a way that all odd position nodes are together and all even positions node are together, Examples: Input: 1-&gt;2-&gt;3-&gt;4 Output: 1-&gt;3-&gt;2-&gt;4 Input: 10-&gt;22-&gt;30-&gt;43-&gt;56-&gt;70 Output: 10-&gt;30-&gt;56-&gt;22-&gt;43-&gt;70Recommended: Please solve it on "PRACTICE" first, before moving on to the
3 min read
Javascript Program For Segregating Even And Odd Nodes In A Linked List
Given a Linked List of integers, write a function to modify the linked list such that all even numbers appear before all the odd numbers in the modified linked list. Also, keep the order of even and odd numbers same. Examples: Input: 17-&gt;15-&gt;8-&gt;12-&gt;10-&gt;5-&gt;4-&gt;1-&gt;7-&gt;6-&gt;NULL Output: 8-&gt;12-&gt;10-&gt;4-&gt;6-&gt;17-&gt;
6 min read
Modify Binary Tree by replacing all nodes at even and odd levels by their nearest even or odd perfect squares respectively
Given a Binary Tree consisting of N nodes, the task is to replace all the nodes that are present at even-numbered levels in a Binary Tree with their nearest even perfect square and replace nodes at odd-numbered levels with their nearest odd perfect square. Examples: Input: 5 / \ 3 2 / \ 16 19 Output: 9 / \ 4 4 / \ 9 25 Explanation: Level 1: Nearest
13 min read
Javascript Program To Merge A Linked List Into Another Linked List At Alternate Positions
Given two linked lists, insert nodes of the second list into the first list at alternate positions of the first list. For example, if first list is 5-&gt;7-&gt;17-&gt;13-&gt;11 and second is 12-&gt;10-&gt;2-&gt;4-&gt;6, the first list should become 5-&gt;12-&gt;7-&gt;10-&gt;17-&gt;2-&gt;13-&gt;4-&gt;11-&gt;6 and second list should become empty. The
3 min read
Rearrange Odd and Even values in Alternate Fashion in Ascending Order
Given an array of integers (both odd and even), the task is to arrange them in such a way that odd and even values come in alternate fashion in non-decreasing order(ascending) respectively. If the smallest value is Even then we have to print Even-Odd pattern.If the smallest value is Odd then we have to print Odd-Even pattern. Note: No. of odd eleme
16 min read