 GeeksforGeeks App
Open App Browser
Continue

# Rearrange 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->2->3->4
Output:  1->3->2->4

Input:   10->22->30->43->56->70
Output:  10->30->56->22->43->70```
Recommended Practice

The important thing in this question is to make sure that all below cases are handled

2. A linked list with only one node
3. A linked list with only two nodes
4. A linked list with an odd number of nodes
5. A linked list with an even number of nodes

The below program maintains two pointers ‘odd’ and ‘even’ for current nodes at odd and even positions respectively. We also store the first node of even linked list so that we can attach the even list at the end of odd list after all odd and even nodes are connected together in two different lists.

Implementation:

## C++

 `// C++ program to rearrange a linked list in such a``// way that all odd positioned node are stored before``// all even positioned nodes``#include``using` `namespace` `std;` `// Linked List Node``class` `Node``{``    ``public``:``    ``int` `data;``    ``Node* next;``};` `// A utility function to create a new node``Node* newNode(``int` `key)``{``    ``Node *temp = ``new` `Node;``    ``temp->data = key;``    ``temp->next = NULL;``    ``return` `temp;``}` `// Rearranges given linked list such that all even``// positioned nodes are before odd positioned.``// Returns new head of linked List.``Node *rearrangeEvenOdd(Node *head)``{``    ``// Corner case``    ``if` `(head == NULL)``        ``return` `NULL;` `    ``// Initialize first nodes of even and``    ``// odd lists``    ``Node *odd = head;``    ``Node *even = head->next;` `    ``// Remember the first node of even list so``    ``// that we can connect the even list at the``    ``// end of odd list.``    ``Node *evenFirst = even;` `    ``while` `(1)``    ``{``        ``// If there are no more nodes, then connect``        ``// first node of even list to the last node``        ``// of odd list``        ``if` `(!odd || !even || !(even->next))``        ``{``            ``odd->next = evenFirst;``            ``break``;``        ``}` `        ``// Connecting odd nodes``        ``odd->next = even->next;``        ``odd = even->next;` `        ``// If there are NO more even nodes after``        ``// current odd.``        ``if` `(odd->next == NULL)``        ``{``            ``even->next = NULL;``            ``odd->next = evenFirst;``            ``break``;``        ``}` `        ``// Connecting even nodes``        ``even->next = odd->next;``        ``even = odd->next;``    ``}` `    ``return` `head;``}` `// A utility function to print a linked list``void` `printlist(Node * node)``{``    ``while` `(node != NULL)``    ``{``        ``cout << node->data << ``"->"``;``        ``node = node->next;``    ``}``    ``cout << ``"NULL"` `<< endl;``}` `// Driver code``int` `main(``void``)``{``    ``Node *head = newNode(1);``    ``head->next = newNode(2);``    ``head->next->next = newNode(3);``    ``head->next->next->next = newNode(4);``    ``head->next->next->next->next = newNode(5);` `    ``cout << ``"Given Linked List\n"``;``    ``printlist(head);` `    ``head = rearrangeEvenOdd(head);` `    ``cout << ``"Modified Linked List\n"``;``    ``printlist(head);` `    ``return` `0;``}` `// This is code is contributed by rathbhupendra`

## C

 `// C program to rearrange a linked list in such a``// way that all odd positioned node are stored before``// all even positioned nodes``#include``using` `namespace` `std;` `// Linked List Node``struct` `Node``{``    ``int` `data;``    ``struct` `Node* next;``};` `// A utility function to create a new node``Node* newNode(``int` `key)``{``    ``Node *temp = ``new` `Node;``    ``temp->data = key;``    ``temp->next = NULL;``    ``return` `temp;``}` `// Rearranges given linked list such that all even``// positioned nodes are before odd positioned.``// Returns new head of linked List.``Node *rearrangeEvenOdd(Node *head)``{``    ``// Corner case``    ``if` `(head == NULL)``        ``return` `NULL;` `    ``// Initialize first nodes of even and``    ``// odd lists``    ``Node *odd = head;``    ``Node *even = head->next;` `    ``// Remember the first node of even list so``    ``// that we can connect the even list at the``    ``// end of odd list.``    ``Node *evenFirst = even;` `    ``while` `(1)``    ``{``        ``// If there are no more nodes, then connect``        ``// first node of even list to the last node``        ``// of odd list``        ``if` `(!odd || !even || !(even->next))``        ``{``            ``odd->next = evenFirst;``            ``break``;``        ``}` `        ``// Connecting odd nodes``        ``odd->next = even->next;``        ``odd = even->next;` `        ``// If there are NO more even nodes after``        ``// current odd.``        ``if` `(odd->next == NULL)``        ``{``            ``even->next = NULL;``            ``odd->next = evenFirst;``            ``break``;``        ``}` `        ``// Connecting even nodes``        ``even->next = odd->next;``        ``even = odd->next;``    ``}` `    ``return` `head;``}` `// A utility function to print a linked list``void` `printlist(Node * node)``{``    ``while` `(node != NULL)``    ``{``        ``cout << node->data << ``"->"``;``        ``node = node->next;``    ``}``    ``cout << ``"NULL"` `<< endl;``}` `// Driver code``int` `main(``void``)``{``    ``Node *head = newNode(1);``    ``head->next = newNode(2);``    ``head->next->next = newNode(3);``    ``head->next->next->next = newNode(4);``    ``head->next->next->next->next = newNode(5);` `    ``cout << ``"Given Linked List\n"``;``    ``printlist(head);` `    ``head = rearrangeEvenOdd(head);` `    ``cout << ``"\nModified Linked List\n"``;``    ``printlist(head);` `    ``return` `0;``}`

## Java

 `// Java program to rearrange a linked list``// in such a way that all odd positioned ``// node are stored before all even positioned nodes``class` `GfG``{` `// Linked List Node``static` `class` `Node``{``    ``int` `data;``    ``Node next;``}` `// A utility function to create a new node``static` `Node newNode(``int` `key)``{``    ``Node temp = ``new` `Node();``    ``temp.data = key;``    ``temp.next = ``null``;``    ``return` `temp;``}` `// Rearranges given linked list``// such that all even positioned``// nodes are before odd positioned.``// Returns new head of linked List.``static` `Node rearrangeEvenOdd(Node head)``{``    ``// Corner case``    ``if` `(head == ``null``)``        ``return` `null``;` `    ``// Initialize first nodes of even and``    ``// odd lists``    ``Node odd = head;``    ``Node even = head.next;` `    ``// Remember the first node of even list so``    ``// that we can connect the even list at the``    ``// end of odd list.``    ``Node evenFirst = even;` `    ``while` `(``1` `== ``1``)``    ``{``        ``// If there are no more nodes, ``        ``// then connect first node of even ``        ``// list to the last node of odd list``        ``if` `(odd == ``null` `|| even == ``null` `||``                        ``(even.next) == ``null``)``        ``{``            ``odd.next = evenFirst;``            ``break``;``        ``}` `        ``// Connecting odd nodes``        ``odd.next = even.next;``        ``odd = even.next;` `        ``// If there are NO more even nodes ``        ``// after current odd.``        ``if` `(odd.next == ``null``)``        ``{``            ``even.next = ``null``;``            ``odd.next = evenFirst;``            ``break``;``        ``}` `        ``// Connecting even nodes``        ``even.next = odd.next;``        ``even = odd.next;``    ``}``    ``return` `head;``}` `// A utility function to print a linked list``static` `void` `printlist(Node node)``{``    ``while` `(node != ``null``)``    ``{``        ``System.out.print(node.data + ``"->"``);``        ``node = node.next;``    ``}``    ``System.out.println(``"NULL"``) ;``}` `// Driver code``public` `static` `void` `main(String[] args)``{``    ``Node head = newNode(``1``);``    ``head.next = newNode(``2``);``    ``head.next.next = newNode(``3``);``    ``head.next.next.next = newNode(``4``);``    ``head.next.next.next.next = newNode(``5``);` `    ``System.out.println(``"Given Linked List"``);``    ``printlist(head);` `    ``head = rearrangeEvenOdd(head);` `    ``System.out.println(``"Modified Linked List"``);``    ``printlist(head);``}``}` `// This code is contributed by Prerna saini`

## Python3

 `# Python3 program to rearrange a linked list``# in such a way that all odd positioned``# node are stored before all even positioned nodes` `# Linked List Node``class` `Node:``    ``def` `__init__(``self``, d):``        ``self``.data ``=` `d``        ``self``.``next` `=` `None` `class` `LinkedList:``    ``def` `__init__(``self``):``        ``self``.head ``=` `None``        ` `    ``# A utility function to create``    ``# a new node``    ``def` `newNode(``self``, key):``        ``temp ``=` `Node(key)``        ``self``.``next` `=` `None``        ``return` `temp` `    ``# Rearranges given linked list``    ``# such that all even positioned``    ``# nodes are before odd positioned.``    ``# Returns new head of linked List.``    ``def` `rearrangeEvenOdd(``self``, head):``        ` `        ``# Corner case``        ``if` `(``self``.head ``=``=` `None``):``            ``return` `None` `        ``# Initialize first nodes of``        ``# even and odd lists``        ``odd ``=` `self``.head``        ``even ``=` `self``.head.``next` `        ``# Remember the first node of even list so``        ``# that we can connect the even list at the``        ``# end of odd list.``        ``evenFirst ``=` `even` `        ``while` `(``1` `=``=` `1``):``            ` `            ``# If there are no more nodes,``            ``# then connect first node of even``            ``# list to the last node of odd list``            ``if` `(odd ``=``=` `None` `or` `even ``=``=` `None` `or``                              ``(even.``next``) ``=``=` `None``):``                ``odd.``next` `=` `evenFirst``                ``break` `            ``# Connecting odd nodes``            ``odd.``next` `=` `even.``next``            ``odd ``=` `even.``next` `            ``# If there are NO more even nodes``            ``# after current odd.``            ``if` `(odd.``next` `=``=` `None``):``                ``even.``next` `=` `None``                ``odd.``next` `=` `evenFirst``                ``break` `            ``# Connecting even nodes``            ``even.``next` `=` `odd.``next``            ``even ``=` `odd.``next``        ``return` `head` `    ``# A utility function to print a linked list``    ``def` `printlist(``self``, node):``        ``while` `(node !``=` `None``):``            ``print``(node.data, end ``=` `"")``            ``print``(``"->"``, end ``=` `"")``            ``node ``=` `node.``next``        ``print` `(``"NULL"``)``        ` `    ``# Function to insert a new node``    ``# at the beginning``    ``def` `push(``self``, new_data):``        ``new_node ``=` `Node(new_data)``        ``new_node.``next` `=` `self``.head``        ``self``.head ``=` `new_node` `# Driver code``ll ``=` `LinkedList()``ll.push(``5``)``ll.push(``4``)``ll.push(``3``)``ll.push(``2``)``ll.push(``1``)``print` `(``"Given Linked List"``)``ll.printlist(ll.head)` `start ``=` `ll.rearrangeEvenOdd(ll.head)` `print` `(``"\nModified Linked List"``)``ll.printlist(start)` `# This code is contributed by Prerna Saini`

## C#

 `// C# program to rearrange a linked list``// in such a way that all odd positioned``// node are stored before all even positioned nodes``using` `System;` `class` `GfG``{` `    ``// Linked List Node``    ``class` `Node``    ``{``        ``public` `int` `data;``        ``public` `Node next;``    ``}` `    ``// A utility function to create a new node``    ``static` `Node newNode(``int` `key)``    ``{``        ``Node temp = ``new` `Node();``        ``temp.data = key;``        ``temp.next = ``null``;``        ``return` `temp;``    ``}` `    ``// Rearranges given linked list``    ``// such that all even positioned``    ``// nodes are before odd positioned.``    ``// Returns new head of linked List.``    ``static` `Node rearrangeEvenOdd(Node head)``    ``{``        ``// Corner case``        ``if` `(head == ``null``)``            ``return` `null``;` `        ``// Initialize first nodes of even and``        ``// odd lists``        ``Node odd = head;``        ``Node even = head.next;` `        ``// Remember the first node of even list so``        ``// that we can connect the even list at the``        ``// end of odd list.``        ``Node evenFirst = even;` `        ``while` `(1 == 1)``        ``{``            ``// If there are no more nodes,``            ``// then connect first node of even``            ``// list to the last node of odd list``            ``if` `(odd == ``null` `|| even == ``null` `||``                            ``(even.next) == ``null``)``            ``{``                ``odd.next = evenFirst;``                ``break``;``            ``}` `            ``// Connecting odd nodes``            ``odd.next = even.next;``            ``odd = even.next;` `            ``// If there are NO more even nodes``            ``// after current odd.``            ``if` `(odd.next == ``null``)``            ``{``                ``even.next = ``null``;``                ``odd.next = evenFirst;``                ``break``;``            ``}` `            ``// Connecting even nodes``            ``even.next = odd.next;``            ``even = odd.next;``        ``}``        ``return` `head;``    ``}` `    ``// A utility function to print a linked list``    ``static` `void` `printlist(Node node)``    ``{``        ``while` `(node != ``null``)``        ``{``            ``Console.Write(node.data + ``"->"``);``            ``node = node.next;``        ``}``        ``Console.WriteLine(``"NULL"``) ;``    ``}` `    ``// Driver code``    ``public` `static` `void` `Main()``    ``{``        ``Node head = newNode(1);``        ``head.next = newNode(2);``        ``head.next.next = newNode(3);``        ``head.next.next.next = newNode(4);``        ``head.next.next.next.next = newNode(5);` `        ``Console.WriteLine(``"Given Linked List"``);``        ``printlist(head);` `        ``head = rearrangeEvenOdd(head);` `        ``Console.WriteLine(``"Modified Linked List"``);``        ``printlist(head);``    ``}``}` `/* This code is contributed PrinciRaj1992 */`

## Javascript

 ``

Output

```Given Linked List
1->2->3->4->5->NULL
1->3->5->2->4->NULL```

Time complexity: O(n) since using a loop to traverse the list, where n is the size of the linked list
Auxiliary Space: O(1)

This article is contributed by Harsh Parikh.Please see here another code contributed by Gautam Singh.If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

### A More Clean Concise Code:

Approach:

1. Have 4 Pointers
2. OddStart, OddEnd, EvenStart, EvenEnd.
3. As the names are made, the pointers also point in such a way.
4. Atlast simply connect the end of Odd List to Start of Even List.
5. Mark the Even List End as NULL.

## C++

 `// C++ Code in Odd -> Even Index Position``#include``using` `namespace` `std;` `// Linked List Node``struct` `Node``{``    ``int` `data;``    ``struct` `Node* next;``};` `// A utility function to create a new node``Node* newNode(``int` `key)``{``    ``Node *temp = ``new` `Node;``    ``temp->data = key;``    ``temp->next = NULL;``    ``return` `temp;``}`  `void` `rearrangeEvenOdd(Node *head)``{``  ``if``(head==NULL || head->next == NULL){``    ``// 0 or 1 node``    ``return``;``  ``}``  ``Node* temp = head;``  ``Node* oddStart = NULL; ``//ODD INDEX``  ``Node* oddEnd = NULL;``  ``Node* evenStart = NULL; ``//EVEN INDEX``  ``Node* evenEnd = NULL;` `  ``int` `i = 1;``  ``while``(temp != NULL){` `    ``if``(i%2 ==0){``      ``//even``      ``if``(evenStart == NULL){``        ``evenStart = temp;` `      ``}``      ``else``{``        ``evenEnd->next = temp;` `      ``}``      ``evenEnd = temp;``    ``}``    ``else``{``      ``//odd``      ``if``(oddStart == NULL){``        ``oddStart = temp;``      ``}``      ``else``{``        ``oddEnd->next = temp;``      ``}``      ``oddEnd = temp;``    ``}``    ``temp = temp->next;``    ``i++;``  ``}` `  ``//now join the odd end with even start``  ``oddEnd->next = evenStart;``  ``//even end is new end so put NULL``  ``evenEnd->next = NULL;` `  ``head = oddStart; ``//new head``}` `void` `printlist(Node * node)``{``    ``while` `(node != NULL)``    ``{``        ``cout << node->data << ``"->"``;``        ``node = node->next;``    ``}``    ``cout << ``"NULL"` `<< endl;``}` `// Driver code``int` `main(``void``)``{``    ``Node *head = newNode(1);``    ``head->next = newNode(2);``    ``head->next->next = newNode(3);``    ``head->next->next->next = newNode(4);``    ``head->next->next->next->next = newNode(5);``    ``head->next->next->next->next->next = newNode(6);` `    ``cout << ``"Given Linked List\n"``;``    ``printlist(head);` `    ``rearrangeEvenOdd(head);` `    ``cout << ``"\nModified Linked List\n"``;``    ``printlist(head);` `    ``return` `0;``}`

## Java

 `// Java program to rearrange a linked list``// in such a way that all odd positioned``// node are stored before all even positioned nodes``import` `java.util.*;` `// Linked List Node``class` `Node {``  ``int` `data;``  ``Node next;``  ``Node(``int` `data)``  ``{``    ``this``.data = data;``    ``this``.next = ``null``;``  ``}``}` `class` `LinkedList {``  ``Node head;``  ``LinkedList() { ``this``.head = ``null``; }``  ``// A utility function to create``  ``// a new node``  ``Node newNode(``int` `key)``  ``{``    ``Node temp = ``new` `Node(key);``    ``temp.next = ``null``;``    ``return` `temp;``  ``}``  ``// Function to rearrane the Linked List``  ``Node rearrangeEvenOdd(Node head)``  ``{``    ``// Corner case``    ``if` `(head == ``null` `|| head.next == ``null``) {``      ``return` `null``;``    ``}``    ``Node temp = head;``    ``Node oddStart = ``null``;``    ``Node oddEnd = ``null``;``    ``Node evenStart = ``null``;``    ``Node evenEnd = ``null``;``    ``int` `i = ``1``;``    ``while` `(temp != ``null``) {``      ``if` `(i % ``2` `== ``0``) {``        ``// even``        ``if` `(evenStart == ``null``) {``          ``evenStart = temp;``        ``}``        ``else` `{``          ``evenEnd.next = temp;``        ``}``        ``evenEnd = temp;``      ``}``      ``else` `{``        ``// odd``        ``if` `(oddStart == ``null``) {``          ``oddStart = temp;``        ``}``        ``else` `{``          ``oddEnd.next = temp;``        ``}``        ``oddEnd = temp;``      ``}``      ``temp = temp.next;``      ``i = i + ``1``;``    ``}``    ``oddEnd.next = evenStart;``    ``evenEnd.next = ``null``;``    ``return` `oddStart;``  ``}``  ``// A utility function to print a linked list``  ``void` `printlist(Node node)``  ``{``    ``while` `(node != ``null``) {``      ``System.out.print(node.data + ``"->"``);``      ``node = node.next;``    ``}``    ``System.out.println(``"NULL"``);``  ``}``  ``// Function to insert a new node``  ``// at the beginning``  ``void` `push(``int` `new_data)``  ``{``    ``Node new_node = ``new` `Node(new_data);``    ``new_node.next = head;``    ``head = new_node;``  ``}``}` `class` `Main {``  ``// Driver code``  ``public` `static` `void` `main(String[] args)``  ``{``    ``LinkedList ll = ``new` `LinkedList();``    ``ll.push(``6``);``    ``ll.push(``5``);``    ``ll.push(``4``);``    ``ll.push(``3``);``    ``ll.push(``2``);``    ``ll.push(``1``);``    ``System.out.println(``"Given Linked List"``);``    ``ll.printlist(ll.head);``    ``Node start = ll.rearrangeEvenOdd(ll.head);``    ``System.out.println(``"\nModified Linked List"``);``    ``ll.printlist(start);``  ``}``}` `// This code is contributed by Tapesh(tapeshdua420)`

## Python3

 `# Python3 program to rearrange a linked list``# in such a way that all odd positioned``# node are stored before all even positioned nodes` `# Linked List Node``class` `Node:``    ``def` `__init__(``self``, data):``        ``self``.data ``=` `data``        ``self``.``next` `=` `None` `class` `LinkedList:``    ``def` `__init__(``self``):``        ``self``.head ``=` `None` `    ``# A utility function to create``    ``# a new node``    ``def` `newNode(``self``, key):``        ``temp ``=` `Node(key)``        ``self``.``next` `=` `None``        ``return` `temp` `    ``# Function to rearrane the Linked List``    ``def` `rearrangeEvenOdd(``self``, head):``        ``# Corner case``        ``if` `(``self``.head ``=``=` `None` `or` `self``.head.``next` `=``=` `None``):``            ``return` `None` `        ``temp ``=` `self``.head``        ``oddStart ``=` `None``        ``oddEnd ``=` `None``        ``evenStart ``=` `None``        ``evenEnd ``=` `None` `        ``i ``=` `1` `        ``while` `(temp ``is` `not` `None``):``            ``if``(i ``%` `2` `=``=` `0``):``              ``# even``              ``if` `evenStart ``is` `None` `:``                  ``evenStart ``=` `temp``              ``else``:``                  ``evenEnd.``next` `=` `temp``              ``evenEnd ``=` `temp``            ``else``:``              ``#odd``              ``if` `oddStart ``is` `None` `:``                  ``oddStart ``=` `temp``              ``else``:``                  ``oddEnd.``next` `=` `temp``              ``oddEnd ``=` `temp``            ``temp ``=` `temp.``next``            ``i ``=` `i``+``1` `        ``oddEnd.``next` `=` `evenStart``        ``evenEnd.``next` `=` `None``        ``return` `oddStart` `    ``# A utility function to print a linked list``    ``def` `printlist(``self``, node):``        ``while` `(node !``=` `None``):``            ``print``(node.data, end``=``"")``            ``print``(``"->"``, end``=``"")``            ``node ``=` `node.``next``        ``print``(``"NULL"``)` `    ``# Function to insert a new node``    ``# at the beginning``    ``def` `push(``self``, new_data):``        ``new_node ``=` `Node(new_data)``        ``new_node.``next` `=` `self``.head``        ``self``.head ``=` `new_node` `# Driver code``ll ``=` `LinkedList()``ll.push(``6``)``ll.push(``5``)``ll.push(``4``)``ll.push(``3``)``ll.push(``2``)``ll.push(``1``)``print``(``"Given Linked List"``)``ll.printlist(ll.head)` `start ``=` `ll.rearrangeEvenOdd(ll.head)` `print``(``"\nModified Linked List"``)``ll.printlist(start)` `# This code is contributed by Yash Agarwal(yashagarwal2852002)`

## C#

 `// C# Program to rearrange a linked list``// in such a way that all odd positioned``// node are stored before all even positioned nodes` `using` `System;` `class` `GfG{` `  ``// Linked List Node``  ``class` `Node{``    ``public` `int` `data;``    ``public` `Node next;``  ``}` `  ``// A utility function of create a new Node``  ``static` `Node newNode(``int` `key){``    ``Node temp = ``new` `Node();``    ``temp.data = key;``    ``temp.next = ``null``;``    ``return` `temp;``  ``}` `  ``// Function to rearrange Linked list``  ``static` `Node rearrangeEvenOdd(Node head){``    ``// Corner Case``    ``if``(head == ``null` `|| head.next == ``null``) ``return` `null``;` `    ``Node temp = head;``    ``Node oddStart = ``null``;``    ``Node oddEnd = ``null``;``    ``Node evenStart = ``null``;``    ``Node evenEnd = ``null``;` `    ``int` `i = 1;``    ``while``(temp != ``null``){``      ``if``(i%2 == 0){``        ``//even``        ``if``(evenStart == ``null``) evenStart = temp;``        ``else` `evenEnd.next = temp;` `        ``evenEnd = temp;``      ``}``else``{``        ``//odd``        ``if``(oddStart == ``null``) oddStart = temp;``        ``else` `oddEnd.next = temp;` `        ``oddEnd = temp;``      ``}``      ``temp = temp.next;``      ``i++;``    ``}` `    ``// now join the odd ned with even start``    ``oddEnd.next = evenStart;``    ``evenEnd.next = ``null``;``    ``return` `oddStart;``  ``}``  ``static` `void` `printlist(Node node)``  ``{``    ``while` `(node != ``null``)``    ``{``      ``Console.Write(node.data + ``"->"``);``      ``node = node.next;``    ``}``    ``Console.WriteLine(``"NULL"``) ;``  ``}` `  ``// Driver code``  ``public` `static` `void` `Main()``  ``{``    ``Node head = newNode(1);``    ``head.next = newNode(2);``    ``head.next.next = newNode(3);``    ``head.next.next.next = newNode(4);``    ``head.next.next.next.next = newNode(5);``    ``head.next.next.next.next.next = newNode(6);` `    ``Console.WriteLine(``"Given Linked List"``);``    ``printlist(head);` `    ``head = rearrangeEvenOdd(head);` `    ``Console.WriteLine(``"\nModified Linked List"``);``    ``printlist(head);``  ``}``}` `/* This code is contributed Yash Agarwal(yashagarwal2852002) */`

## Javascript

 `// JavaScript program to rearrange a linked list``// in such a way that all odd positioned``// node are stored before all even positioned nodes` `// Linked List Node``class Node {``    ``constructor(data) {``        ``this``.data = data;``        ``this``.next = ``null``;``    ``}``}` `class LinkedList {``    ``constructor() {``        ``this``.head = ``null``;``    ``}` `    ``// A utility function to create``    ``// a new node``    ``newNode(key) {``        ``temp = ``new` `Node(key);``        ``this``.next = ``null``;``        ``return` `temp;``    ``}` `    ``// Function to rearrane the Linked List``    ``rearrangeEvenOdd(head) {``        ``// Corner case``        ``if` `(``this``.head == ``null` `|| ``this``.head.next == ``null``) {``            ``return` `null``;``        ``}` `        ``var` `temp = ``this``.head;``        ``var` `oddStart = ``null``;``        ``var` `oddEnd = ``null``;``        ``var` `evenStart = ``null``;``        ``var` `evenEnd = ``null``;` `        ``var` `i = 1;` `        ``while` `(temp != ``null``) {``            ``if` `(i % 2 == 0) {``                ``// even``                ``if` `(evenStart == ``null``) {``                    ``evenStart = temp;``                ``} ``else` `{``                    ``evenEnd.next = temp;``                ``}``                ``evenEnd = temp;``            ``} ``else` `{``                ``//odd``                ``if` `(oddStart == ``null``) {``                    ``oddStart = temp;``                ``} ``else` `{``                    ``oddEnd.next = temp;``                ``}``                ``oddEnd = temp;``            ``}``            ``temp = temp.next;``            ``i = i + 1;``        ``}` `        ``oddEnd.next = evenStart;``        ``evenEnd.next = ``null``;``        ``return` `oddStart;``    ``}` `    ``// A utility function to print a linked list``    ``printlist(node) {``        ``while` `(node != ``null``) {``            ``process.stdout.write(node.data+``"->"``);``            ``node = node.next;``        ``}``        ``console.log(``"NULL"``);``    ``}` `    ``// Function to insert a new node``    ``// at the beginning``    ``push(new_data) {``        ``var` `new_node = ``new` `Node(new_data);``        ``new_node.next = ``this``.head;``        ``this``.head = new_node;``    ``}``}` `// Driver code``ll = ``new` `LinkedList();``ll.push(6);``ll.push(5);``ll.push(4);``ll.push(3);``ll.push(2);``ll.push(1);``console.log(``"Given Linked List"``);``ll.printlist(ll.head);` `start = ll.rearrangeEvenOdd(ll.head);` `console.log(``"\nModified Linked List"``);``ll.printlist(start);` `// This code is contributed by Tapesh(tapeshdua420)`

Output

```Given Linked List
1->2->3->4->5->6->NULL

1->3->5->2->4->6->NULL```

Time complexity: O(n) since using a loop to traverse the list, where n is the size of the linked list
Auxiliary Space: O(1) As only few pointers.

## Approach:

To rearrange the linked list in such a way that all odd-positioned nodes are together and all even-positioned nodes are together, we can follow the following steps:

1. We will create two separate linked lists, one for odd-positioned nodes and the other for even-positioned nodes.
2. We will traverse the original linked list, and for each node, we will check its position.
3. If the position is odd, we will add that node to the odd-positioned linked list, and if the position is even, we will add that node to the even-positioned linked list.
4. Once we have added all the nodes to their respective linked lists, we will merge these two linked lists to form the final rearranged linked list.

Steps:

2. Traverse the original linked list using the curr pointer.
3. For each node, check its position using a counter variable.
4. If the position is odd, add that node to the end of the odd-positioned linked list and update the odd_head pointer if necessary.
5. If the position is even, add that node to the end of the even-positioned linked list and update the even_head pointer if necessary.
6. Once we have traversed the entire original linked list, merge the odd_positioned linked list and the even_positioned linked list to form the final rearranged linked list.
7. Return the rearranged linked list.

## C++

 `#include ` `using` `namespace` `std;` `struct` `ListNode {``    ``int` `val;``    ``ListNode* next;``    ``ListNode(``int` `x) : val(x), next(NULL) {}``};` `ListNode* rearrange_linked_list(ListNode* head) {``    ``// Initialize pointers``    ``ListNode* odd_head = ``new` `ListNode(0);``    ``ListNode* odd = odd_head;``    ``ListNode* even_head = ``new` `ListNode(0);``    ``ListNode* even = even_head;``    ``ListNode* curr = head;``    ``int` `counter = 1;` `    ``// Traverse the original linked list``    ``while` `(curr) {``        ``if` `(counter % 2 == 1) {``            ``// Odd-positioned node``            ``odd->next = curr;``            ``odd = odd->next;``        ``}``        ``else` `{``            ``// Even-positioned node``            ``even->next = curr;``            ``even = even->next;``        ``}` `        ``// Move to the next node``        ``curr = curr->next;``        ``counter++;``    ``}` `    ``// Merge the odd-positioned linked list and the even-positioned linked list``    ``odd->next = even_head->next;``    ``even->next = NULL;` `    ``// Return the rearranged linked list``    ``return` `odd_head->next;``}` `int` `main() {``    ``// Create the linked list 1->2->3->4``    ``ListNode* head = ``new` `ListNode(1);``    ``head->next = ``new` `ListNode(2);``    ``head->next->next = ``new` `ListNode(3);``    ``head->next->next->next = ``new` `ListNode(4);` `    ``// Rearrange the linked list``    ``ListNode* new_head = rearrange_linked_list(head);` `    ``// Print the rearranged linked list``    ``while` `(new_head) {``        ``cout << new_head->val << ``"->"``;``        ``new_head = new_head->next;``    ``}` `    ``return` `0;``}``//This code is written by Abhay_Mishra`

## Java

 `class` `ListNode {``    ``int` `val;``    ``ListNode next;``    ``ListNode(``int` `val, ListNode next) {``        ``this``.val = val;``        ``this``.next = next;``    ``}``    ``ListNode(``int` `val) {``        ``this``(val, ``null``);``    ``}``}` `class` `Solution {``    ``public` `ListNode rearrangeLinkedList(ListNode head) {``        ``// Initialize pointers``        ``ListNode oddHead = ``new` `ListNode(``0``), odd = oddHead;``        ``ListNode evenHead = ``new` `ListNode(``0``), even = evenHead;``        ``ListNode curr = head;``        ``int` `counter = ``1``;``        ` `        ``// Traverse the original linked list``        ``while` `(curr != ``null``) {``            ``if` `(counter % ``2` `== ``1``) {``                ``// Odd-positioned node``                ``odd.next = curr;``                ``odd = odd.next;``            ``} ``else` `{``                ``// Even-positioned node``                ``even.next = curr;``                ``even = even.next;``            ``}``            ` `            ``// Move to the next node``            ``curr = curr.next;``            ``counter++;``        ``}``        ` `        ``// Merge the odd-positioned linked list and the even-positioned linked list``        ``odd.next = evenHead.next;``        ``even.next = ``null``;``        ` `        ``// Return the rearranged linked list``        ``return` `oddHead.next;``    ``}``}` `public` `class` `Main {``    ``public` `static` `void` `main(String[] args) {``        ``// Create the linked list 1->2->3->4``        ``ListNode head = ``new` `ListNode(``1``, ``new` `ListNode(``2``, ``new` `ListNode(``3``, ``new` `ListNode(``4``))));``        ` `        ``// Rearrange the linked list``        ``Solution solution = ``new` `Solution();``        ``ListNode newHead = solution.rearrangeLinkedList(head);``        ` `        ``// Print the rearranged linked list``        ``while` `(newHead != ``null``) {``            ``System.out.print(newHead.val + ``"->"``);``            ``newHead = newHead.next;``        ``}``    ``}``}`

## Python3

 `class` `ListNode:``    ``def` `__init__(``self``, val``=``0``, ``next``=``None``):``        ``self``.val ``=` `val``        ``self``.``next` `=` `next` `def` `rearrange_linked_list(head: ListNode) ``-``> ListNode:``    ``# Initialize pointers``    ``odd_head ``=` `odd ``=` `ListNode(``0``)``    ``even_head ``=` `even ``=` `ListNode(``0``)``    ``curr ``=` `head``    ``counter ``=` `1``    ` `    ``# Traverse the original linked list``    ``while` `curr:``        ``if` `counter ``%` `2` `=``=` `1``:``            ``# Odd-positioned node``            ``odd.``next` `=` `curr``            ``odd ``=` `odd.``next``        ``else``:``            ``# Even-positioned node``            ``even.``next` `=` `curr``            ``even ``=` `even.``next``        ` `        ``# Move to the next node``        ``curr ``=` `curr.``next``        ``counter ``+``=` `1``    ` `    ``# Merge the odd-positioned linked list and the even-positioned linked list``    ``odd.``next` `=` `even_head.``next``    ``even.``next` `=` `None``    ` `    ``# Return the rearranged linked list``    ``return` `odd_head.``next` `# Create the linked list 1->2->3->4``head ``=` `ListNode(``1``, ListNode(``2``, ListNode(``3``, ListNode(``4``))))` `# Rearrange the linked list``new_head ``=` `rearrange_linked_list(head)` `# Print the rearranged linked list``while` `new_head:``    ``print``(new_head.val, end``=``"->"``)``    ``new_head ``=` `new_head.``next`

## Javascript

 `class ListNode {``    ``constructor(val = 0, next = ``null``) {``        ``this``.val = val;``        ``this``.next = next;``    ``}``}` `function` `rearrangeLinkedList(head) {``    ``// Initialize pointers``    ``let oddHead = odd = ``new` `ListNode(0);``    ``let evenHead = even = ``new` `ListNode(0);``    ``let curr = head;``    ``let counter = 1;``    ` `    ``// Traverse the original linked list``    ``while` `(curr) {``        ``if` `(counter % 2 === 1) {``            ``// Odd-positioned node``            ``odd.next = curr;``            ``odd = odd.next;``        ``} ``else` `{``            ``// Even-positioned node``            ``even.next = curr;``            ``even = even.next;``        ``}``        ` `        ``// Move to the next node``        ``curr = curr.next;``        ``counter++;``    ``}``    ` `    ``// Merge the odd-positioned linked list and the even-positioned linked list``    ``odd.next = evenHead.next;``    ``even.next = ``null``;``    ` `    ``// Return the rearranged linked list``    ``return` `oddHead.next;``}` `// Create the linked list 1->2->3->4``let head = ``new` `ListNode(1, ``new` `ListNode(2, ``new` `ListNode(3, ``new` `ListNode(4))));` `// Rearrange the linked list``let newHead = rearrangeLinkedList(head);` `// Print the rearranged linked list``while` `(newHead) {``    ``console.log(newHead.val + ``"->"``);``    ``newHead = newHead.next;``}`

Output

`1->3->2->4->`

Time complexity: The time complexity of the above algorithm is O(n), where n is the number of nodes in the linked list.
Auxiliary space: The auxiliary space used by the above algorithm is O(1)

My Personal Notes arrow_drop_up