I am trying to write a method that sorts the elements in a doubly linked list. The list is made up of structs with a forward and backward pointer (flink, blink) to the next element. head->blink should be null, tail->flink should be null (aka not circular). I tried a selection sort approach but I keep getting a segmentation fault. I have isolated the problem into the commented lines. However I included all of my code, the sort method is at the bottom.
//header (dblLinkList.h)
#include <stdio.h>
#include <stdlib.h>
typedef struct _DblLinkList {
struct _DblLinkList *flink;
struct _DblLinkList *blink;
int num;
} DblLinkList;
struct _DblLinkList *head, *tail;
struct _DblLinkList *init(int nElements);
void sort(struct _DblLinkList *listNode);
void print(struct _DblLinkList *listNode);
//implementation
#include <stdio.h>
#include <stdlib.h>
#include "dblLinkList.h"
int main() {
struct _DblLinkList *list1 = init(2);
printf("-----Head to Tail------\n");
print(list1);
printf("Sorting...\n");
sort(list1);
printf("-----Head to Tail------\n");
print(list1);
}
struct _DblLinkList *init(int nElements) {
struct _DblLinkList *listNode;
int i = 0;
for(i = 0; i < nElements; i++) {
listNode = (struct _DblLinkList *)malloc(sizeof(struct _DblLinkList));
listNode->num = random();
if(head == NULL) {
head = listNode;
listNode->blink = NULL;
} else {
tail->flink = listNode;
listNode->blink = tail;
}
tail = listNode;
listNode->flink = NULL;
}
return listNode;
}
void print(struct _DblLinkList *listNode) {
for(listNode = head; listNode != NULL; listNode = listNode->flink) {
printf("%d\n", listNode->num);
}
}
void sort(struct _DblLinkList *listNode) {
//Not working properly
struct _DblLinkList *listNode2;
struct _DblLinkList *minNode;
struct _DblLinkList *temp = (struct _DblLinkList *)malloc(sizeof(struct _DblLinkList));
//start from the head and traverse the list
for(listNode = head; listNode != NULL; listNode = listNode->flink) {
minNode = listNode;
listNode2 = listNode->flink;
for(;listNode2 != NULL; listNode2 = listNode2->flink) {
if (listNode2->num < minNode->num) {
minNode = listNode2;
}
}
//Problem Lies here vvvvvvvvvvvv
temp->flink = listNode->flink;
temp->blink = listNode->blink;
listNode->blink = listNode2;
listNode->flink = listNode2->flink;
listNode2->flink = temp;
listNode2->blink = temp->blink;
printf("min: %d\n", minNode->num);
}
}