#给定一个单链表,把所有的奇数节点和偶数节点分别排在一起。这里的奇数节点和偶数节点指的是节点编号的奇偶性,不是值的奇偶性。 |
class ListNode: |
def __init__( self , val = 0 , next = None ): |
self .val = val |
self . next = next |
def oddEvenList(head): |
if not head: |
return head |
odd = head |
even = head. next |
even_head = even |
while even and even. next : |
odd. next = even. next |
odd = odd. next |
even. next = odd. next |
even = even. next |
odd. next = even_head |
return head |
# Test Cases |
def createLinkedList(arr): |
if not arr: |
return None |
head = ListNode(arr[ 0 ]) |
curr = head |
for i in range ( 1 , len (arr)): |
curr. next = ListNode(arr[i]) |
curr = curr. next |
return head |
def printLinkedList(head): |
if not head: |
return |
curr = head |
while curr: |
print (curr.val, end = " " ) |
curr = curr. next |
print () |
# Test Case 1 |
arr = [ 1 , 2 , 3 , 4 , 5 ] |
head = createLinkedList(arr) |
print ( "Input:" ) |
printLinkedList(head) |
head = oddEvenList(head) |
print ( "Output:" ) |
printLinkedList(head) |
# Test Case 2 |
arr = [ 2 , 1 , 3 , 5 , 6 , 4 , 7 ] |
head = createLinkedList(arr) |
print ( "Input:" ) |
printLinkedList(head) |
head = oddEvenList(head) |
print ( "Output:" ) |
printLinkedList(head) |