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.
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 ...
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def oddEvenList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head:
return None
pre = head
cur = head.next
while cur and cur.next:
# pre指向当前奇节点的末尾
tmp = pre.next
pre.next = cur.next
cur.next =cur.next.next
pre.next.next = tmp
cur = cur.next
pre = pre.next
return head