I am having some trouble translating this java code in to C. There is something wrong with my merge sort in C. Don't know what since I get error at runtime.
Compiler: Dev-cpp 4.8.8.0
OS: Windows 2000 sp4
"Java"
Code:
public static IntNode MergeSort(IntNode list1)
{
if ((list1 == null) || (list1.getLink() == null)
return list1;
IntNode list2 = split(list1);
list1 = MergeSort(list1);
list2 = MergeSort(list2);
return merge(list1, list2);
}
private static IntNode split(IntNode list1)
{
if ((list1 == null) || (list1.getLink() == null)
return null;
IntNode.list2 = list1.getLink();
list1.setLink(list2.getLink());
list2.setLink(split(list2.getLink()));
return list2;
}
private static IntNode merge(IntNode list1, IntNode list2)
{
if (list1 == null)
return list2;
if (list2 == null)
return list1;
if (list1.getData() < list2.getData())
{
list1.setLink(merge(list1.getLink(), list2));
return list1;
}
else
{
list2.setLink(merge(list1, list2.getLink()));
return list2;
}
}
This is what I have done in C.
INTLINKEDLIST.H
Code:
#ifndef _INTLINKEDLIST_H_
#define _INTLINKEDLIST_H_
struct Node
{
int element;
struct Node * Next;
};
void Insert(int x, struct Node * l);
struct Node * MergeSort(struct Node * list1);
struct Node * split(struct Node * list1);
struct Node * merge(struct Node * list1, struct Node * list2);
#endif
Code:
#include "IntLinkedList.h"
#include <stdio.h>
#include <stdlib.h>
void insert(int X, struct Node * l)
{
struct Node * temp = malloc(sizeof(struct Node));
if (temp == NULL)
fprintf(stderr, "Error in memory allocation.\n");
temp->element = X;
temp->Next = l->Next;
l->Next = temp;
}
struct Node * MergeSort(struct Node * list1)
{
struct Node * list2;
if ((list1 == NULL) || (list1->Next == NULL))
return list1;
list2 = split(list1);
list1 = MergeSort(list1);
list2 = MergeSort(list2);
return merge(list1, list2);
}
struct Node * split(struct Node * list1)
{
struct Node * list2;
if ((list1 == NULL) || (list2->Next == NULL))
return NULL;
list2 = list1->Next;
list1->Next = list2->Next;
list2->Next = split(list2->Next);
return list2;
}
struct Node * merge(struct Node * list1, struct Node * list2)
{
if (list1 == NULL)
return list2;
if (list2 == NULL)
return list1;
if (list1->element < list2->element)
{
list1->Next = merge(list1->Next, list2);
return list1;
}
else
{
list2->Next = merge(list1, list2->Next);
return list2;
}
}