Alternate Odd and Even Nodes in a Singly Linked List
Last Updated :
11 Jan, 2023
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 current node is even and it occurs at an odd position, push this node's address to stack Even
- Step 4: If 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 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
Implementation:
C++
// CPP program to rearrange nodes
// as alternate odd even nodes in
// a Singly Linked List
#include <bits/stdc++.h>
using namespace std;
// Structure node
struct Node {
int data;
struct Node* next;
};
// A utility function to print
// linked list
void printList(struct Node* node)
{
while (node != NULL) {
cout << node->data << " ";
node = node->next;
}
cout << endl;
}
// Function to create newNode
// in a linkedlist
Node* newNode(int key)
{
Node* temp = new Node;
temp->data = key;
temp->next = NULL;
return temp;
}
// Function to insert at beginning
Node* insertBeg(Node* head, int val)
{
Node* temp = newNode(val);
temp->next = head;
head = temp;
return head;
}
// Function to rearrange the
// odd and even nodes
void rearrangeOddEven(Node* head)
{
stack<Node*> odd;
stack<Node*> even;
int i = 1;
while (head != nullptr) {
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.empty() && !even.empty()) {
// Swap Data at the top of two stacks
swap(odd.top()->data, even.top()->data);
odd.pop();
even.pop();
}
}
// Driver code
int main()
{
Node* 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);
cout << "Linked List:" << endl;
printList(head);
rearrangeOddEven(head);
cout << "Linked List after "
<< "Rearranging:" << endl;
printList(head);
return 0;
}
Java
// Java program to rearrange nodes
// as alternate odd even nodes in
// a Singly Linked List
import java.util.*;
class GFG
{
// class node
static class Node
{
int data;
Node next;
}
// A utility function to print
// linked list
static void printList(Node node)
{
while (node != null)
{
System.out.print(node.data +" ");
node = node.next;
}
System.out.println();
}
// Function to create newNode
// in a linkedlist
static Node newNode(int key)
{
Node temp = new Node();
temp.data = key;
temp.next = null;
return temp;
}
// Function to insert at beginning
static Node insertBeg(Node head, int val)
{
Node temp = newNode(val);
temp.next = head;
head = temp;
return head;
}
// Function to rearrange the
// odd and even nodes
static void rearrangeOddEven(Node head)
{
Stack<Node> odd=new Stack<Node>();
Stack<Node> even=new Stack<Node>();
int 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.size() > 0 && even.size() > 0)
{
// Swap Data at the top of two stacks
int k=odd.peek().data;
odd.peek().data=even.peek().data;
even.peek().data=k;
odd.pop();
even.pop();
}
}
// Driver code
public static void main(String args[])
{
Node 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);
System.out.println( "Linked List:" );
printList(head);
rearrangeOddEven(head);
System.out.println( "Linked List after "+
"Rearranging:" );
printList(head);
}
}
// This contributed by Arnab Kundu
Python
# Python program to rearrange nodes
# as alternate odd even nodes in
# a Singly Linked List
# Link list node
class Node:
def __init__(self, data):
self.data = data
self.next = next
# A utility function to print
# linked list
def printList( node):
while (node != None) :
print(node.data , end=" ")
node = node.next
print("\n")
# Function to create newNode
# in a linkedlist
def newNode(key):
temp = Node(0)
temp.data = key
temp.next = None
return temp
# Function to insert at beginning
def insertBeg(head, val):
temp = newNode(val)
temp.next = head
head = temp
return head
# Function to rearrange the
# odd and even nodes
def rearrangeOddEven( head):
odd = []
even = []
i = 1
while (head != None):
if (head.data % 2 != 0 and i % 2 == 0):
# Odd Value in Even Position
# Add pointer to current node
# in odd stack
odd.append(head)
elif (head.data % 2 == 0 and i % 2 != 0):
# Even Value in Odd Position
# Add pointer to current node
# in even stack
even.append(head)
head = head.next
i = i + 1
while (len(odd) != 0 and len(even) != 0) :
# Swap Data at the top of two stacks
odd[-1].data, even[-1].data = even[-1].data, odd[-1].data
odd.pop()
even.pop()
return head
# Driver code
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)
print( "Linked List:" )
printList(head)
rearrangeOddEven(head)
print( "Linked List after ", "Rearranging:" )
printList(head)
# This code is contributed by Arnab Kundu
C#
// C# program to rearrange nodes
// as alternate odd even nodes in
// a Singly Linked List
using System;
using System.Collections.Generic;
class GFG
{
// class node
public class Node
{
public int data;
public Node next;
}
// A utility function to print
// linked list
static void printList(Node node)
{
while (node != null)
{
Console.Write(node.data +" ");
node = node.next;
}
Console.WriteLine();
}
// Function to create newNode
// in a linkedlist
static Node newNode(int key)
{
Node temp = new Node();
temp.data = key;
temp.next = null;
return temp;
}
// Function to insert at beginning
static Node insertBeg(Node head, int val)
{
Node temp = newNode(val);
temp.next = head;
head = temp;
return head;
}
// Function to rearrange the
// odd and even nodes
static void rearrangeOddEven(Node head)
{
Stack<Node> odd = new Stack<Node>();
Stack<Node> even = new Stack<Node>();
int 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.Count > 0 && even.Count > 0)
{
// Swap Data at the top of two stacks
int k=odd.Peek().data;
odd.Peek().data=even.Peek().data;
even.Peek().data=k;
odd.Pop();
even.Pop();
}
}
// Driver code
public static void Main(String []args)
{
Node 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);
Console.WriteLine( "Linked List:" );
printList(head);
rearrangeOddEven(head);
Console.WriteLine( "Linked List after "+
"Rearranging:" );
printList(head);
}
}
// This code has been contributed by 29AjayKumar
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 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)
- Segregate odd and even values in the list. After this, all odd values will occur together followed by all even values.
- Split the list into two lists odd and even.
- 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
Implementation:
C++
// Cpp program to rearrange nodes
// as alternate odd even nodes in
// a Singly Linked List
#include <bits/stdc++.h>
using namespace std;
// Structure node
struct Node {
int data;
struct Node* next;
};
// A utility function to print
// linked list
void printList(struct Node* node)
{
while (node != NULL) {
cout << node->data << " ";
node = node->next;
}
cout << endl;
}
// Function to create newNode
// in a linkedlist
Node* newNode(int key)
{
Node* temp = new Node;
temp->data = key;
temp->next = NULL;
return temp;
}
// Function to insert at beginning
Node* insertBeg(Node* head, int val)
{
Node* temp = newNode(val);
temp->next = head;
head = temp;
return head;
}
// Function to rearrange the
// odd and even nodes
void rearrange(Node** head)
{
// Step 1: Segregate even and odd nodes
// Step 2: Split odd and even lists
// Step 3: Merge even list into odd list
Node* even;
Node *temp, *prev_temp;
Node *i, *j, *k, *l, *ptr;
// Step 1: Segregate Odd and Even Nodes
temp = (*head)->next;
prev_temp = *head;
while (temp != nullptr) {
// Backup next pointer of temp
Node* 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 != nullptr && temp->data % 2 != 0) {
prev_temp = temp;
temp = temp->next;
}
even = temp;
// End the odd List (Make last node null)
prev_temp->next = nullptr;
// Step 3:
// Merge Even List into odd
i = *head;
j = even;
while (j != nullptr && i != nullptr) {
// 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 == nullptr) {
// 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
}
// Driver Code
int main()
{
Node* 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);
cout << "Linked List:" << endl;
printList(head);
cout << "Rearranged List" << endl;
rearrange(&head);
printList(head);
}
Java
// Java program to rearrange nodes
// as alternate odd even nodes in
// a Singly Linked List
class GFG
{
// Structure node
static class Node
{
int data;
Node next;
};
// A utility function to print
// linked list
static void printList(Node node)
{
while (node != null)
{
System.out.print(node.data + " ");
node = node.next;
}
System.out.println();
}
// Function to create newNode
// in a linkedlist
static Node newNode(int key)
{
Node temp = new Node();
temp.data = key;
temp.next = null;
return temp;
}
// Function to insert at beginning
static Node insertBeg(Node head, int val)
{
Node temp = newNode(val);
temp.next = head;
head = temp;
return head;
}
// Function to rearrange the
// odd and even nodes
static Node rearrange(Node head)
{
// Step 1: Segregate even and odd nodes
// Step 2: Split odd and even lists
// Step 3: Merge even list into odd list
Node even;
Node temp, prev_temp;
Node 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
Node 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
public static void main(String args[])
{
Node 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);
System.out.println("Linked List:" );
printList(head);
System.out.println("Rearranged List" );
head=rearrange(head);
printList(head);
}
}
// This code is contributed by Arnab Kundu
Python3
# Python3 program to rearrange nodes
# as alternate odd even nodes in
# a Singly Linked List
# Structure node
class Node :
def __init__(self):
self.data = 0
self.next = None
# A utility function to print
# linked list
def printList(node) :
while (node != None) :
print(node.data, end = " ")
node = node.next
print(" ")
# Function to create newNode
# in a linkedlist
def newNode( key) :
temp = Node()
temp.data = key
temp.next = None
return temp
# Function to insert at beginning
def insertBeg( head, val) :
temp = newNode(val)
temp.next = head
head = temp
return head
# Function to rearrange the
# odd and even nodes
def rearrange(head) :
# Step 1: Segregate even and odd nodes
# Step 2: Split odd and even lists
# Step 3: Merge even list into odd list
even = None
temp = None
prev_temp = None
i = None
j = None
k = None
l = None
ptr = None
# Step 1: Segregate Odd and Even Nodes
temp = (head).next
prev_temp = head
while (temp != None) :
# Backup next pointer of temp
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 != None and temp.data % 2 != 0) :
prev_temp = temp
temp = temp.next
even = temp
# End the odd List (Make last node None)
prev_temp.next = None
# Step 3:
# Merge Even List into odd
i = head
j = even
while (j != None and i != None):
# 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 == None):
# 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
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)
print("Linked List:" )
printList(head)
print("Rearranged List" )
head = rearrange(head)
printList(head)
# This code is contributed by Arnab Kundu
C#
// C# program to rearrange nodes
// as alternate odd even nodes in
// a Singly Linked List
using System;
class GFG
{
// Structure node
public class Node
{
public int data;
public Node next;
};
// A utility function to print
// linked list
static void printList(Node node)
{
while (node != null)
{
Console.Write(node.data + " ");
node = node.next;
}
Console.WriteLine();
}
// Function to create newNode
// in a linkedlist
static Node newNode(int key)
{
Node temp = new Node();
temp.data = key;
temp.next = null;
return temp;
}
// Function to insert at beginning
static Node insertBeg(Node head, int val)
{
Node temp = newNode(val);
temp.next = head;
head = temp;
return head;
}
// Function to rearrange the
// odd and even nodes
static Node rearrange(Node head)
{
// Step 1: Segregate even and odd nodes
// Step 2: Split odd and even lists
// Step 3: Merge even list into odd list
Node even;
Node temp, prev_temp;
Node 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
Node 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
public static void Main(String []args)
{
Node 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);
Console.WriteLine("Linked List:" );
printList(head);
Console.WriteLine("Rearranged List" );
head=rearrange(head);
printList(head);
}
}
// This code is contributed by Rajput-Ji
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 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)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem