# 328. Odd Even Linked List 奇偶链表

@TOC

## # 题目描述

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:
Given 1->2->3->4->5->NULL,
return 1->3->5->2->4->NULL.
``````

Note:

1. The relative order inside both the even and odd groups should remain as it was in the input.
2. The first node is considered odd, the second node even and so on ...

## # 解题方法

Python代码如下：

``````# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
"""
:rtype: ListNode
"""
odd = ListNode(0)
even = ListNode(0)
index = 0
if index & 1 == 0:
odd = odd.next
else:
even = even.next
index += 1
even.next = None
``````

C++代码如下，不过由于在函数中声明了普通指针而没有delete，会造成内存泄漏，leetcode能通过，但是面试的时候要小心。

``````/**
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
int index = 1;
if (index & 1) {
odd = odd->next;
} else {
even = even->next;
}
++index;
}
if (even->next) even->next = nullptr;
}
};
``````

## # 日期

2018 年 3 月 15 日 —— 雾霾消散，春光明媚 2019 年 3 月 23 日 —— 一年之后重刷此题，还是还有点生疏