# LeetCode 328：奇偶链表 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.

输入: 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
return head

26746 0

9554 0

11269 0

13251 0
windows server 2008阿里云ECS服务器安全设置

9068 0

6965 0

4063 0
+关注

85

0

《2021云上架构与运维峰会演讲合集》

《零基础CSS入门教程》

《零基础HTML入门教程》