fix: fixed test case failing

This commit is contained in:
weiss-ben 2022-09-24 01:03:33 +03:00
parent 49c2e2a721
commit 4c1400dbcb

View File

@ -70,6 +70,7 @@ ListNode* middleNode(ListNode* head) {
slowptr = slowptr->next; slowptr = slowptr->next;
fastptr = fastptr->next->next; fastptr = fastptr->next->next;
} }
return (fastptr->next) ? slowptr->next : slowptr; return (fastptr->next) ? slowptr->next : slowptr;
} }
} // namespace median_search2 } // namespace median_search2
@ -80,51 +81,57 @@ ListNode* middleNode(ListNode* head) {
* @returns void * @returns void
*/ */
static void test() { static void test() {
auto* head = new ListNode; auto* head1 = new ListNode;
head->val = 1; head1->val = 1;
ListNode* temp1 = head; ListNode* temp = head1;
for (int i = 1; i < 6; ++i) { for (int i = 1; i < 6; ++i) {
auto temp2 = new ListNode; auto* temp1 = new ListNode;
temp2->val = i; temp1->val = i;
temp1->next = temp2; temp->next = temp1;
temp1 = temp2; temp = temp1;
} }
ListNode* median = search::median_search2::middleNode(head); ListNode* median = search::median_search2::middleNode(head1);
assert(3 == median->val); // 3 is the value of the median node. assert(3 == median->val); // 3 is the value of the median node.
std::cout << "test case:1 passed\n"; std::cout << "test case:1 passed\n";
// Clean up // Clean up
while (head) { while (head1) {
ListNode* t = head; ListNode* t = head1;
head = head->next; head1 = head1->next;
delete t; delete t;
} }
delete head1;
head = new ListNode; delete temp;
head->val = 1;
// Test case # 2
temp1 = head; auto* head2 = new ListNode;
head2->val = 1;
ListNode* temp2 = head2;
for (int i = 1; i < 7; ++i) { for (int i = 1; i < 7; ++i) {
auto temp2 = new ListNode; auto temp3 = new ListNode;
temp2->val = i; temp3->val = i;
temp1->next = temp2; temp2->next = temp3;
temp1 = temp2; temp2 = temp3;
} }
median = search::median_search2::middleNode(head); median = search::median_search2::middleNode(head2);
assert(4 == median->val); // 3 is the value of the median node. assert(4 == median->val); // 4 is the value of the median node.
std::cout << "test case:1 passed\n"; std::cout << "test case:1 passed\n";
// Clean up // Clean up
while (head) { while (head2) {
ListNode* t = head; ListNode* t = head2;
head = head->next; head2 = head2->next;
delete t; delete t;
} }
delete head2;
delete temp2;
std::cout << "test case:2 passed\n"; std::cout << "test case:2 passed\n";
std::cout << "--All tests passed--\n"; std::cout << "--All tests passed--\n";
} }