- 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.
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 ...
Credits:
Special thanks to @DjangoUnchained for adding this problem and creating all test cases.
my thoughts:
1. two pointers.
my solution:
********** 96ms
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def oddEvenList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head or not head.next or not head.next.next:
return head
slow = head
fast = head.next
while fast and fast.next:
temp = slow.next
slow.next = fast.next
fast.next = fast.next.next
slow.next.next = temp
slow = slow.next
fast = fast.next
return head
my comments:
from other ppl's solution:
1. faster, 56ms:
class Solution:
def oddEvenList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head == None:
return
origeven = head.next
odd = head
even = head.next
oddrunner = head
evenrunner = even
while oddrunner and evenrunner:
oddrunner = oddrunner.next
if oddrunner:
oddrunner = oddrunner.next
evenrunner = evenrunner.next
if evenrunner:
evenrunner = evenrunner.next
odd.next = oddrunner
if odd.next:
odd = odd.next
#print("odd")
#print(odd.val)
even.next = evenrunner
if even.next:
even = even.next
#print("even")
#print(even.val)
odd.next = origeven
return head