Mam napisane sortowanie dla listy jednokierunkowej
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<conio.h>
#define STRMAX 256
struct TLine
{
int number;
char line[STRMAX];
};
struct TNode
{
struct TLine data;
struct TNode* next;
//struct TNode* prev;
};
/*struct TList{
struct TNode* head;
struct TNode* tail;
};*/
void initList(struct TNode** head)
{
(*head)=NULL;
}
int isEmpty(struct TNode* head)
{
return (head==NULL);
}
void push(struct TNode** head,struct TLine l)
{
struct TNode* newNode;
newNode=(struct TNode*)malloc(sizeof(struct TNode));
newNode->data.number=l.number;
strcpy(newNode->data.line,l.line);
newNode->next=(*head);
(*head)=newNode;
}
void pop(struct TNode** head, struct TLine* l)
{
struct TNode* temp;
if(!isEmpty(*head))
{
temp=(*head);
l->number=temp->data.number;
strcpy(l->line,temp->data.line);
(*head)=(*head)->next;
free(temp);
}
}
void split(struct TNode* head,struct TNode** front,struct TNode** back)
{
struct TNode* slow;
struct TNode* fast;
if(head==NULL||head->next==NULL)
{
(*front)=head;
(*back)=NULL;
}
else
{
slow=head;
fast=head->next;
while(fast!=NULL)
{
fast=fast->next;
if(fast!=NULL)
{
slow=slow->next;
fast=fast->next;
}
}
(*front)=head;
(*back)=slow->next;
slow->next=NULL;
}
}
struct TNode* merge(struct TNode* h1,struct TNode* h2)
{
struct TNode *tmp=NULL;
struct TNode *newl=NULL;
if(h1==NULL) newl=h2;
else if(h2==NULL) newl=h1;
else
{
if(strcmp(h1->data.line,h2->data.line)<=0)
{
newl=h1;
h1=h1->next;
}
else
{
newl=h2;
h2=h2->next;
}
tmp=newl;
while(h1!=NULL&&h2!=NULL)
{
if(strcmp(h1->data.line,h2->data.line)<=0)
{
tmp->next=h1;
h1=h1->next;
}
else
{
tmp->next=h2;
h2=h2->next;
}
tmp=tmp->next;
}
if(h1==NULL) tmp->next=h2;
else tmp->next=h1;
}
return newl;
};
void mergesort(struct TNode** head)
{
struct Node* h1=NULL;
struct Node* h2=NULL;
if((*head)!=NULL&&(*head)->next!=NULL)
{
split((*head),&h1,&h2);
mergesort(&h1);
mergesort(&h2);
(*head)=merge(h1,h2);
}
}
int main()
{
struct TLine l;
char esc;
int i,n;
struct TNode* head=NULL;
do
{
initList(&head);
printf("Podaj liczbe wezlow\n");
scanf("%d",&n);
getchar();
i=1;
while(i<=n)
{
printf("Podaj lancuch\n");
fgets(l.line,STRMAX,stdin);
//scanf("%d",&l.number);
l.number=i;
push(&head,l);
i++;
}
mergesort(&head);
while(!isEmpty(head))
{
pop(&head,&l);
printf("%d %s\n",l.number,l.line);
}
esc=getch();
}
while(esc!=27);
return 0;
}
Co należy zmienić aby sortowanie działało na liście dwukierunkowej