Skip to content

Instantly share code, notes, and snippets.

@ritik-agrawal
Created February 5, 2025 07:06
Show Gist options
  • Save ritik-agrawal/98be82d7605716a73de571ff9dc51d9b to your computer and use it in GitHub Desktop.
Save ritik-agrawal/98be82d7605716a73de571ff9dc51d9b to your computer and use it in GitHub Desktop.
Odd Even Linked 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) {
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;
}
}
@ritik-agrawal
Copy link
Author

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment