LeetCode: Odd Even Linked List Solution

2 pointers running simultaneously

Approach

2 pointers: head for odd and head for even (in terms of original index)

Implementation

1var oddEvenList = function (head) {
2 if (!head || !head.next) {
3 return head
4 }
5
6 let oddHead = (oddTail = head)
7 let evenHead = (evenTail = head.next)
8
9 while (oddTail && oddTail.next && evenTail && evenTail.next) {
10 oddTail.next = oddTail.next.next
11 oddTail = oddTail.next
12
13 evenTail.next = evenTail.next.next
14 evenTail = evenTail.next
15 }
16
17 oddTail.next = evenHead
18
19 return oddHead
20}

References

Original problem

Similar problems

Split Linked List in Parts

Comments

Loading comments...

Tags

leetcode

linked list

Next Post

LeetCode: Merge Two Sorted Lists

(IMO) Not easy as categorized

Previous Post

HoningJS

Search Posts