[Java][LetCode][LinkedList] Odd Even Linked List #328

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.

You must solve the problem in O(1) extra space complexity and O(n) time complexity.
Input: head = [1,2,3,4,5]
Output: [1,3,5,2,4]

解了兩次,第一次的rumtime是1ms,再把程式稍微整理一下,第二次就比較俐落一點。
概念是這樣的,分成兩個node list,一個是奇數,一個是偶數,奇數的初始化指到head,偶數的初始化指到head.next。將奇偶node交替放到自己的list中,直到even出了邊界。最後將偶數的list串到奇數的後面,回傳奇數list。

My approach is :
create two list: odd and even list. Initiation the odd list from head, and initiation even list is from head.next. Alternate the odd list and the even list each other. Until, the even list is out of bound. At last, add the even list after the odd list.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store