# Simple O(N) time, O(1), space Java solution.

• ``````public class Solution {
public ListNode oddEvenList(ListNode head) {
if (head != null) {

ListNode odd = head, even = head.next, evenHead = even;

while (even != null && even.next != null) {
odd.next = odd.next.next;
even.next = even.next.next;
odd = odd.next;
even = even.next;
}
odd.next = evenHead;
}
return head;
}}``````

• this is very simple and elegant.

• This post is deleted!

• @xuyirui

I was the first person who got this elegant solution

Maybe. But you weren't the first who posted it. That was yangneu2015.

• This post is deleted!

• Very smart and clean solution.

• Beautiful solution, brilliant.

• NICE! ELEGANT! NICE AND ELEGANT!

• i don't think it is `in place`

• what if the linked list has odd number of elements? won't that make us 'lose' the last element if we use
while even and even.next?

• This post is deleted!

• we have the same idea to solve this problem, but your code is much shorter than me, can you tell me how you did this, I want to improve my skills,how can i do this? can you teach me some skills?

• @psnr

It works for odd lengths as well; the next odd will be set to the final odd, and the next even will be set to null, then the loop ends.

@禽兽样

It is in place, since changing the odd and even values modifies the original list structure.

• agree with you.

• This solution also assumes that the values inside of the nodes are going to be the same as the number of the order in which they appear. We're not ordering them by the intrinsic property of whether their order number in the list is odd or even, but rather by the oddness or evenness of the numbers they contain

The problem would allow a list like
1,6,9,4,5,7,3. This solution would not work there.

• @jason165 No. Try reading the problem. Especially the second sentence.

• OH. missed that. My bad.

• Rule of thumb: A solution with +65 votes is very unlikely that fundamentally wrong :-P

• Why have to use evenhead?
Why not just odd.next = head.next?

• Because head.next is not the evenhead.
Note in the first execution of "odd.next = odd.next.next; " sets head.next to the third element.

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.