LeetCode – Odd Even Linked List (Java)


Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes.

The program should run in O(1) space complexity and O(nodes) time complexity.


Given 1->2->3->4->5->NULL,
return 1->3->5->2->4->NULL.


This problem can be solved by using two pointers. We iterate over the link and move the two pointers.

Odd Even Linked List

Java Solution

public ListNode oddEvenList(ListNode head) {
    if(head == null) 
        return head;
    ListNode result = head;
    ListNode p1 = head;
    ListNode p2 = head.next;
    ListNode connectNode = head.next;
    while(p1 != null && p2 != null){
            ListNode t = p2.next;
            if(t == null)
            p1.next = p2.next;
            p1 = p1.next;
            p2.next = p1.next;
            p2 = p2.next;
    p1.next = connectNode;
    return result;
Category >> Algorithms  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
String foo = "bar";
  • prasahnth

    I know my code has little bit complexity. But I feel like wanna post my code. I paid a lot of time to get the correct output.

  • prashanth

    Node pre=head;

    Node cur=head.next;

    Node later=cur.next;


    Node temp=pre.next;

    Node temp1=later.next;







  • Lekan Osagie

    My solution ollows the same principle as the other solutions.
    public class Solution {
    public ListNode oddEvenList(ListNode head) {

    if(head == null){return head;}

    ListNode odd = head;

    ListNode even = head.next;

    ListNode evenStart = even;

    while(even != null && even.next != null)
    odd.next = even.next;

    odd = odd.next;

    even.next = odd.next;

    even = even.next;
    odd.next = evenStart;

    return head;

  • Hi Admin . I just wanted a moment to thank you for providing short understandable solutions for problems here , It has been a great help 🙂

  • Alina

    Could just have the following code, and not need Node t:

    while (p1 != null && p2 != null && p2.next != null) {

    p1.next = p2.next;// Connect to next odd node

    p1 = p1.next;// Move odd pointer

    p2.next = p1.next;// Connect to next even node

    p2 = p2.next;// Move even pointer

    } // end while

    p1.next = connectNode;// Connect evens to odds
    return result;

    }// end oddEvenList