Created
August 28, 2024 07:55
-
-
Save s1nisteR/b8cde273b5d026769ff5d0b827d3d8e0 to your computer and use it in GitHub Desktop.
Linked List Odd Even Question: https://www.interviewbit.com/linked-list-interview-questions/#rearrange-a-linked-list-such-that-all-even-numbers-are-positioned-before-odd-numbers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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