List类题型:odd Even Linked List

Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes.

You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity.

Example:

Given1->2->3->4->5->NULL,

return1->3->5->2->4->NULL.

Note:

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

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

这道题虽然是Medium Level, 但是还是挺简单的。

一开始做可能会有一个误区, 先把Even node整一组, odd node整一组。 但是这么实践一下,会发现本来的索引会被改变。 例如 1-->2-->3-->4-->5.    1本来要靠2的索引找到3,但是现在2的索引变成了4,那1就到不了3了! 

List类问题做的时候最好画一个Simple case: 例如1->2->3->4

很容易就会发现上述问题,所以解法应该是一个的while loop, 

一遍更改even, odd nodes的索引。

你可能感兴趣的:(List类题型:odd Even Linked List)