Created
February 5, 2025 07:06
-
-
Save ritik-agrawal/98be82d7605716a73de571ff9dc51d9b to your computer and use it in GitHub Desktop.
Odd Even Linked List
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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) { | |
if (head == null || head.next == null || head.next.next == null){ | |
return head; | |
} | |
var odd = head; | |
var even = head.next; | |
var previousEven = new ListNode(); | |
var evenHead = previousEven; | |
while ( | |
odd != null && | |
even != null | |
){ | |
odd.next = even.next; | |
previousEven.next = even; | |
previousEven = previousEven.next; | |
if (odd.next == null){ | |
even = null; | |
} else { | |
odd = odd.next; | |
even = odd.next; | |
} | |
} | |
odd.next = evenHead.next; | |
previousEven.next = null; | |
return head; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
LeetCode
Odd Even Linked List
Achievement
The above question was solved by me that beat 100% of the total submissions in terms of runtime.
Submission link