Merge Two Sorted Linked Lists
Given two sorted linked lists, merge them so that the resulting linked list is also sorted.
We'll cover the following...
Statement
We’re given two sorted linked lists. Merge them so that the resulting linked list is also sorted.
Example
Consider two sorted linked lists as an example:
The merged linked list should look like this:
Sample input
[4, 8, 15, 19, 22]
[7, 9, 10, 16]
Expected output
[4, 7, 8, 9, 10, 15, 16, 19, 22]
Try it yourself
main.cpp
LinkedList.cpp
LinkedListNode.cpp
#include "LinkedList.cpp"using namespace std;typedef LinkedListNode* node_ptr;node_ptr MergeSorted(node_ptr head1, node_ptr head2) {//TODO: Write - Your - Codereturn head1;}
Solution
- We maintain a head and a tail pointer on the merged linked list.
- We choose the head of the merged linked list by comparing the first node of both linked lists.
- For all subsequent nodes in both
Access this course and 1400+ top-rated courses and projects.