Solution
/* struct ListNode {
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
}; */
ListNode* oddEvenList(ListNode* head) {
if (head == nullptr) {
return head;
}
ListNode* oddPointer = head;
ListNode* evenHead = oddPointer->next;
ListNode* evenPointer = evenHead;
while(evenPointer != nullptr && evenPointer->next != nullptr) {
oddPointer->next = evenPointer->next;
oddPointer = oddPointer->next;
evenPointer->next = oddPointer->next;
evenPointer = evenPointer->next;
}
oddPointer->next = evenHead;
return head;
}
Complexity
Runtime: O(n)
Space: O(1)
Top comments (0)