# LeetCode 328：奇偶链表 Odd Even Linked List

2019.07.19 13:19 685浏览

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.

``````输入: 1->2->3->4->5->NULL

``````

``````输入: 2->1->3->5->6->4->7->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 …

### Java：

``````class Solution {
while (even != null && even.next != null) {//循环条件，偶节点遇空时结束
odd.next = even.next;//奇节点指向偶节点的下一个节点
odd = odd.next;//刷新奇链表指针
even.next = odd.next;//偶节点指向奇节点的下一个节点
even = even.next;//刷新偶链表指针
}
odd.next = tmp;//连接双链表
}
}
``````

### Python3：

``````class Solution:
def oddEvenList(self, head: ListNode) -> ListNode:
while even and even.next:
odd.next = even.next
odd = odd.next
even.next = odd.next
even = even.next
odd.next = tmp
``````

0人点赞

• 推荐
• 评论
• 收藏
• 共同学习，写下你的评论

0/150