I have two sorted linked lists, list1 and list2. My goal is to merge list2 into list1.
The requirements are as follows:
- The resulting list should be list1 (no creating a new linked list and having the merged list to be in the new linked list)
- The return type must be void
- list2 must be empty after the merge
- Merged list must be sorted
- Cannot delete or remove any nodes. Move pointers only
- No recursions
- No sorting allowed in the algorithm
- No other helper functions
Sample output:
- list1: d -> e -> f -> t -> w -> x -> y -> NULL
- list2: a -> b -> e -> j -> l -> z -> NULL
Result:
- list1: a -> b -> d -> e -> e -> f -> j -> l -> t -> w -> x -> y -> z -> NULL
- list2: empty
My code's result is currently
- list1: d -> e -> f -> j -> l -> t -> w -> x -> y -> z -> NULL
- list2: a -> b -> d -> e -> e -> f -> j -> l -> t -> w -> x -> y -> z -> NULL
typedef struct listNode {
char data;
struct listNode* nextPtr;
} ListNode;
typedef ListNode* ListNodePtr;
void mergeSortedList(ListNodePtr list1, ListNodePtr list2) {
ListNodePtr curr = NULL;
ListNodePtr last = NULL;
if (list1->data < list2->data)
{
curr = list1;
last = list1;
list1 = list1->nextPtr;
}
else {
curr = list2;
last = list2;
list2 = list2->nextPtr;
}
last->nextPtr = NULL;
while (list1 != NULL && list2 != NULL) {
if (list1->data < list2->data) {
last->nextPtr = list1;
last = list1;
list1 = list1->nextPtr;
}
else {
last->nextPtr = list2;
last = list2;
list2 = list2->nextPtr;
}
last->nextPtr = NULL;
}
if (list1 != NULL) {
last->nextPtr = list1;
}
else {
last->nextPtr = list2;
}
}