Data Structures & Algorithms
Testing Your Linked List
Linked ListsNow that we have implemented all the core functionalities of our LinkedList, let’s write a main() method that will test every function.
If the code runs without any errors, it means you implemented your Linked List correctly!
Test Code:
#include <iostream>
#include <cassert> // For assert()
#include "LinkedList.h"
int main() {
LinkedList list;
// Step 1: Test empty list
assert(list.is_empty()); // Expected: true
assert(list.size() == 0); // Expected: 0
std::cout << "Initial list is empty" << std::endl;
// Step 2: Test push_front and push_back
list.push_front(10);
list.push_front(20);
list.push_front(30); // List: 30 → 20 → 10
list.push_back(5);
list.push_back(40);
list.push_back(50); // List: 30 → 20 → 10 → 5 → 40 → 50
assert(list.size() == 6); // Expected: 6
std::cout << "Insertion tests passed" << std::endl;
// Step 3: Test get_node_at
assert(list.get_node_at(0)->data == 30);
assert(list.get_node_at(2)->data == 10);
assert(list.get_node_at(4)->data == 40);
assert(list.get_node_at(6) == nullptr); // Out-of-bounds test
std::cout << "get_node_at tests passed" << std::endl;
// Step 4: Test get_node_by_value
assert(list.get_node_by_value(20) != nullptr);
assert(list.get_node_by_value(100) == nullptr); // Value does not exist
std::cout << "get_node_by_value tests passed" << std::endl;
// Step 5: Test push_at_n
assert(list.push_at_n(25, 3)); // Insert at index 3
assert(list.size() == 7);
assert(list.get_node_at(3)->data == 25);
std::cout << "push_at_n tests passed" << std::endl;
// Step 6: Test remove_at_n
assert(list.remove_at_n(4)); // Remove index 4
assert(list.size() == 6);
assert(list.get_node_at(4)->data == 40); // 5 was removed
std::cout << "remove_at_n tests passed" << std::endl;
// Step 7: Test invalid remove
assert(!list.remove_at_n(10)); // Out-of-bounds removal
std::cout << "Invalid removal test passed" << std::endl;
// Step 8: Test final list state
list.print_list(); // Should print: 30 → 20 → 10 → 25 → 50 → NULL
assert(list.size() == 6);
std::cout << "Final list state test passed" << std::endl;
std::cout << "\nAll tests passed successfully!" << std::endl;
return 0;
}Members only
Keep reading this lesson
You've reached the end of the free preview. Unlock the rest of this lesson plus 42 more lessons in Data Structures & Algorithms.
- Unlimited coding questions
- Unlimited access to all classroom material
- Weekly live call for questions and guidance
- 3,000 AI tutor tokens / month
- Personal SQL database (3 MB)
- Progress tracking
Cancel any time.