Odd-even LinkedList

Problem

We have to keep index i tracking the node values if i is odd then put them in a different say odd, else put them in a list say even.
At the end connect the last node of the odd list to head of even list

/**
* Definition for singly-linked l…


This content originally appeared on DEV Community and was authored by Prashant Mishra

Problem

We have to keep index i tracking the node values if i is odd then put them in a different say odd, else put them in a list say even.
At the end connect the last node of the odd list to head of even list

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode oddEvenList(ListNode head) {
        ListNode odd  = new ListNode(0);
        ListNode even = new ListNode(0);
        ListNode pointerOfOdd = odd;
        ListNode pointerOfEven = even;
        int i =1;
        while(head!=null){
            if(i%2!=0){
                odd.next = new ListNode(head.val);
                odd = odd.next;
            }
            else{
                even.next = new ListNode(head.val);
                even = even.next;
            }
            i++;
            head = head.next;
        }
        odd.next = pointerOfEven.next;

        return pointerOfOdd.next;
    }
}


This content originally appeared on DEV Community and was authored by Prashant Mishra


Print Share Comment Cite Upload Translate Updates
APA

Prashant Mishra | Sciencx (2024-07-20T15:56:24+00:00) Odd-even LinkedList. Retrieved from https://www.scien.cx/2024/07/20/odd-even-linkedlist/

MLA
" » Odd-even LinkedList." Prashant Mishra | Sciencx - Saturday July 20, 2024, https://www.scien.cx/2024/07/20/odd-even-linkedlist/
HARVARD
Prashant Mishra | Sciencx Saturday July 20, 2024 » Odd-even LinkedList., viewed ,<https://www.scien.cx/2024/07/20/odd-even-linkedlist/>
VANCOUVER
Prashant Mishra | Sciencx - » Odd-even LinkedList. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2024/07/20/odd-even-linkedlist/
CHICAGO
" » Odd-even LinkedList." Prashant Mishra | Sciencx - Accessed . https://www.scien.cx/2024/07/20/odd-even-linkedlist/
IEEE
" » Odd-even LinkedList." Prashant Mishra | Sciencx [Online]. Available: https://www.scien.cx/2024/07/20/odd-even-linkedlist/. [Accessed: ]
rf:citation
» Odd-even LinkedList | Prashant Mishra | Sciencx | https://www.scien.cx/2024/07/20/odd-even-linkedlist/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.