Cześć, jestem podkreślam, dużym newbie jeżeli chodzi o C, pobawiłem się w sortowanie listy, poprzez zrzucanie jej do tablicy wskaźników, teraz tutaj jest moje pytanie, czy jest możliwość takiej konwersji w przypadku listy jednokierunkowej ? w dwukierunkowej wyobrażam sobię, że mogę się zacząć cofać po liście, lecz tutaj jak przejdę do ostatniego elementu, to tak jakby mam wskaźnik ustawiony na ostatni element, więc nie wiem jak mogę się cofnąć od ostatniego, do pierwszego elementu. Poniżej przesyłam kod, poprosiłbym o naprowadzenie na rozwiązanie problemu.
#include <stdlib.h>
#include <stdio.h>
typedef struct Node
{
int data;
struct Node* next;
} Node;
void insert(Node** ,int x);
void print();
void insert_node_at_n(Node**, int, int);
int compare_data(const void* first, const void* second)
{
Node*a=*((Node**)first);
Node*b=*((Node**)second);
if ((a->data)>(b->data)) return -1;
else if((a->data)==(b->data)) return 0;
else return 1;
}
int length_of_list(Node* head)
{
int d=0;
while(head!=NULL)
{
head = head->next;
d++;
}
return d;
}
void sorting(Node*);
int main(void)
{
Node* head ;
head=NULL;
printf("How many numbers? \n");
int n, i, x;
scanf("%d", &n);
for(i=0;i<n;i++)
{
printf("Enter the number \n");
scanf("%d", &x);
insert(&head, x);
}
print(head);
printf("length of list: %d", length_of_list(head));
sorting(head);
return 0;
}
void insert(Node** pointerToHead, int x)
{
Node* temp=(Node*)malloc(sizeof(struct Node));
temp->data = x;
temp->next=*pointerToHead;
if(*pointerToHead != NULL) temp->next=*pointerToHead;
*pointerToHead = temp;
}
void print(Node* head)
{
while(head != NULL)
{
printf("%d \n", head->data);
head = head->next;
}
}
void insert_node_at_n(Node** pointerToHead, int data, int n)
{
Node* temp1 = (Node*)malloc(sizeof(Node*));
temp1->data=data;
temp1->next=NULL;
if(n == 1)
{
temp1->next = *pointerToHead;
*pointerToHead = temp1;
return;
}
Node* temp2 = *pointerToHead;
for(int i=0; i<n-2;i++)
{
temp2=temp2->next;
}
temp1->next = temp2->next;
temp2->next = temp1;
}
void sorting(Node* head)
{
int i=0;
int d=length_of_list(head);
Node** tab=(Node**)malloc(d*sizeof(Node*));
while(head!=NULL)
{
tab[i]=head;
head=head->next;
i++;
}
qsort(tab, i, sizeof(tab), compare_data);
int j=0;
while (j<i) {
printf("%d\t", tab[j]->data);
j++;
}
free(tab);
}