diff --git a/328-odd-even-linked-list/driver.cpp b/328-odd-even-linked-list/driver.cpp new file mode 100644 index 0000000..e2d7f11 --- /dev/null +++ b/328-odd-even-linked-list/driver.cpp @@ -0,0 +1,22 @@ +#include "soln.hpp" + +int main() +{ + ListNode n5 = ListNode(5); + ListNode n4 = ListNode(4, &n5); + ListNode n3 = ListNode(3, &n4); + ListNode n2 = ListNode(2, &n3); + ListNode n1 = ListNode(1, &n2); + + ListNode n_4 = ListNode(4); + ListNode n_2 = ListNode(2, &n_4); + ListNode n_5 = ListNode(5, &n_2); + ListNode n_3 = ListNode(3, &n_5); + ListNode n_1 = ListNode(1, &n_3); + + Solution soln; + soln.printList(&n1); + soln.printList(&n_1); + cout << "Grouped odd-even correctly? " << soln.test(&n1, &n_1) << endl; + return 0; +} \ No newline at end of file diff --git a/328-odd-even-linked-list/soln.cpp b/328-odd-even-linked-list/soln.cpp new file mode 100644 index 0000000..8d2fc16 --- /dev/null +++ b/328-odd-even-linked-list/soln.cpp @@ -0,0 +1,51 @@ +#include "soln.hpp" + +ListNode *Solution::oddEvenList(ListNode *head) +{ + bool odd_node = true; + if (head == nullptr || head->next == nullptr || head->next->next == nullptr) + return head; + ListNode *even_start = head->next; + ListNode *cur_node; + ListNode *next_node = head; + while (next_node) + { + cur_node = next_node; + next_node = cur_node->next; + if (next_node == nullptr) + break; + cur_node->next = cur_node->next->next; + } + cur_node = head; + while (cur_node->next) + cur_node = cur_node->next; + cur_node->next = even_start; + return head; +} + +void Solution::printList(ListNode *head) +{ + ListNode *cur = head; + while (cur) + { + cout << cur->val << " "; + cur = cur->next; + } + cout << endl; +} + +bool Solution::test(ListNode *head, ListNode *answer) +{ + ListNode *cur1 = oddEvenList(head), *ans1 = answer; + while (cur1 && ans1) + { + if (cur1->val != ans1->val) + return false; + cur1 = cur1->next; + ans1 = ans1->next; + } + if (!cur1 && !ans1) + return true; + else + return false; +} \ No newline at end of file diff --git a/328-odd-even-linked-list/soln.hpp b/328-odd-even-linked-list/soln.hpp new file mode 100644 index 0000000..73d05a5 --- /dev/null +++ b/328-odd-even-linked-list/soln.hpp @@ -0,0 +1,20 @@ +#include + +using namespace std; + +/* Singly linked list*/ +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) {} +}; + +class Solution { + public: + ListNode* oddEvenList(ListNode* head); + void printList(ListNode* head); + bool test(ListNode* head, ListNode* answer); +}; \ No newline at end of file