This is the code for my doubly linked list. It works fine. I need help with sorting the data elements of this linked list.
#include <stdio.h>
#include <stdlib.h>
struct Node{
int data;
struct Node* next;
struct Node* prev;
};
struct Node* head;//global variable
int GetNewNode(int x)
{
struct Node* newNode=(struct Node*)malloc(sizeof(struct Node));
newNode->data=x;
newNode->prev=NULL;
newNode->next=NULL;
return newNode;
}
int InsertAtHead(int x)
{
struct Node* newNode =GetNewNode(x);
if(head==NULL)//list empty
{
head=newNode;
return;
}
head->prev=newNode;
newNode->next=head;
head=newNode;
}
void print()
{
struct Node* temp=head;//start printing from head
printf("Forward: ");
while(temp!=NULL)
{
printf("%d ",temp->data);
temp=temp->next;
}
printf("\n");
}
int main()
{
head=NULL;// initially taking it as null
InsertAtHead(2);print();
InsertAtHead(5);print();
InsertAtHead(3);print();
InsertAtHead(9);print();
return 0;
}
I want to sort the Data elements here. I tried this:
void sort()
{
struct Node* temp=head;
int numTemp;
while(temp!=NULL)
{
if(temp->prev > temp->next)
{
numTemp=temp->next;
temp->next= temp->prev;
temp->prev=numTemp;
}
}
}
But this compares the address, not the data of the linked list, How do i compare data and sort them accordingly ?
temp->prev->dataand such. Just don't dereference any NULL pointers. - StoryTeller - Unslander Monica