题目:
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:
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 ...
分析:
- 由于链表的单向性,为满足原址操作的要求,需要定义奇数链表尾部指针和偶数链表头部指针
- 不断在原链表中将奇数节点移动到所有偶数节点之前,当前节点之前节点数目不变,不改变待操作链表节点的奇偶
代码:
class Solution(object):
def oddEvenList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not (head and head.next):
return head
odd = head
even = head.next
evenHead = even
oddEnd = odd
odd = even.next
while odd:
# print odd.val
oddEnd.next = odd
oddEnd = oddEnd.next
even.next = even.next.next
oddEnd.next = evenHead
even = even.next
if even:
odd = even.next
else:
break
return head
思考:
- 当原链表节点数小于3时,无需变换