7.17 Odd Even Linked List
7.17.1 Problem Metadata
- Platform: LeetCode
- Problem ID: 328
- Difficulty: Medium
- URL: https://leetcode.com/problems/odd-even-linked-lc-list/
- Techniques: Linked List
7.17.3 Solution - Two Pointers
7.17.3.1 Walkthrough
Maintain two pointers odd and even, and a evenHead. Traverse the list, linking odd nodes to odd nodes and even nodes to even nodes. Finally, connect the tail of the odd list to evenHead.
7.17.3.3 Code - Java
public ListNode oddEvenList(ListNode head) {
if (head == null) return null;
ListNode odd = head;
ListNode even = head.next;
ListNode evenHead = even;
while (even != null && even.next != null) {
odd.next = even.next;
odd = odd.next;
even.next = odd.next;
even = even.next;
}
odd.next = evenHead;
return head;
}