Skip to content

Instantly share code, notes, and snippets.

@s1nisteR
Created August 28, 2024 07:55
Show Gist options
  • Save s1nisteR/b8cde273b5d026769ff5d0b827d3d8e0 to your computer and use it in GitHub Desktop.
Save s1nisteR/b8cde273b5d026769ff5d0b827d3d8e0 to your computer and use it in GitHub Desktop.
#include <iostream>
using namespace std;
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* oddFirstThenEven(ListNode* head)
{
ListNode* result = new ListNode();
ListNode* evenHead = new ListNode();
ListNode* oddHead = new ListNode();
ListNode* evenExplorer = evenHead;
ListNode* oddExplorer = oddHead;
while(head != nullptr)
{
if(head->val % 2 == 0)
{
evenExplorer->next = head;
evenExplorer = evenExplorer->next;
}
else
{
oddExplorer->next = head;
oddExplorer = oddExplorer->next;
}
head = head->next;
}
result->next = evenHead->next;
evenExplorer->next = oddHead->next;
oddExplorer->next = nullptr;
return result->next;
}
//driver code for testing
int main()
{
ListNode* one = new ListNode(1);
ListNode* two = new ListNode(2);
ListNode* three = new ListNode(3);
ListNode* four = new ListNode(4);
one->next = two;
two->next = three;
three->next = four;
// 1 -> 2 -> 3 -> 4
// 1 -> 3 -> 2 -> 4
ListNode* result = oddFirstThenEven(one);
while(result != nullptr)
{
cout << result->val << "\n";
result = result->next;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment