[Java][LeetCode]Linked List — Odd Even Linked List #328

SP Hou
2 min readMar 12, 2021

Given the head of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return the reordered list.

The first node is considered odd, and the second node is even, and so on.

Note that the relative order inside both the even and odd groups should remain as it was in the input.

Example 1:

Input: head = [1,2,3,4,5]
Output: [1,3,5,2,4]

=================Solve====================

step1. creat a counter from 0, use this counter to judge current Node is odd or even.
step2. creat odd Node and even Node. first odd Node is tmp.val, first even Node is tmp.next.val.
*****IMPORTEN*****
we need to use creat a new ListNode instead of equal tmp Node.
oddNode= new ListNode(tmp.val); ← correct
oddNode = tmp.val; ← error
step3. if counter is odd, add new Node to odd tail node, and set odd tail Node. On the contrary, add new Node to even tail noed.
step4. we point odd tail to even node. string odd node and even node together.

--

--