328. Odd Even Linked List
https://leetcode.com/problems/odd-even-linked-list/
js
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var oddEvenList = function(head) {
if (!head) {
return head;
}
var lastOdd = head;
var current = head.next;
var firstEven;
while (current && current.next) {
firstEven = lastOdd.next;
lastOdd.next = current.next;
lastOdd = lastOdd.next;
current.next = lastOdd.next;
lastOdd.next = firstEven;
current = current.next;
}
return head;
};
py
# 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 head
last_odd, current = head, head.next
while current and current.next:
first_even = last_odd.next
last_odd.next = current.next
last_odd = last_odd.next
current.next = last_odd.next
last_odd.next = first_even
current = current.next
return head