Im trying to resolve the 21. Merge Two Sorted Lists on leetCode. The problem is composed as follows: I have two linked lists already ordered in ascending order and I have to combine them into a single list that is also ordered in ascending order.
This is my code:
struct ListNode *sortList(struct ListNode *headList) {
struct ListNode *ptrHead = headList;
int temp;
if(headList == NULL)
return NULL;
while(ptrHead->next != NULL){
if(ptrHead->val > ptrHead->next->val){
temp = ptrHead->val;
ptrHead->val = ptrHead->next->val;
ptrHead->next->val = temp;
ptrHead = headList;
}else{
ptrHead = ptrHead->next;
}
}
return headList;
}
void addNode(struct ListNode **list, int data){
struct ListNode *newNode = (struct ListNode *) malloc(sizeof (struct ListNode)), *temp = NULL;
if((*list) == NULL){
newNode->val = data;
newNode->next = NULL;
(*list) = newNode;
}else{
temp = (*list);
while (temp->next != NULL){
temp = temp->next;
}
newNode->val = data;
temp->next = newNode;
}
}
struct ListNode *mergeTwoLists(struct ListNode *l1, struct ListNode *l2){
struct ListNode *newList = NULL;
while (l1 != NULL){
addNode(&newList, l1->val);
l1 = l1->next;
}
while (l2 != NULL){
addNode(&newList, l2->val);
l2 = l2->next;
}
return sortList(newList);
}
I tried to run it locally and I had no problem but when I go to run it on the leet code I get an error
The error:
Line 19: Char 20: runtime error: member access within misaligned address
0xbebebebebebebebe for type 'struct ListNode', which requires 8 byte alignment
[solution.c]
0xbebebebebebebebe: note: pointer points here
<memory cannot be printed>