Я пытаюсь выполнить сортировку выбора в односвязном списке, меняя местами сам узел, но после всех входных данных похоже, что моя функция sort () не работает должным образом. Что мне не хватает или что я сделал не так, пожалуйста, помогите мне с этим.
ПРИМЕЧАНИЕ. Название всех функций и указателей в значительной степени говорит об их задаче, поэтому я решил не добавлять комментарии Но если кто-то хочет прокомментировать, дайте мне знать.
ПРИМЕЧАНИЕ. В swap_node(int i, int j)
, i
и j
- это позиции двух узлов, которые необходимо поменять местами.
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int data;
struct node *next;
} node;
node *head = NULL, *prev = NULL, *next = NULL;
static int k = 0;//Global variable K which will store the no of nodes created so far.
node *make_node()
{
k++;
return ((node *)malloc(sizeof(node)));
}
void push()
{
if (k == 0)
{
next = make_node();
printf("Enter Data:");
scanf("%d", &next->data);
next->next = NULL;
head = next;
prev = next;
}
else
{
next = make_node();
printf("Enter Data:");
scanf("%d", &next->data);
next->next = NULL;
prev->next = next;
prev = next;
}
}
node *x = NULL, *y = NULL;
void swap_node(int i, int j)
{
node *prevX = NULL, *currX = head, *prevY = NULL, *currY = head;
if (i == 1)
{
for (int l = 1; l < j; l++)
{
prevY = currY;
currY = currY->next;
}
head = currY;
if (j - i == 1)
{
currX->next = currY->next;
currY->next = currX;
}
else
{
node *temp = currX->next;
currX->next = currY->next;
currY->next = temp;
prevY->next = currX;
}
}
else
{
for (int l = 1; l < i; l++)
{
prevX = currX;
currX = currX->next;
}
for (int l = 1; l < j; l++)
{
prevY = currY;
currY = currY->next;
}
if (j - i == 1)
{
prevX->next = currY;
currX->next = currY->next;
currY->next = currX;
}
else
{
node *temp = currX->next;
prevX->next = currY;
prevY->next = currX;
currX->next = currY->next;
currY->next = temp;
}
}
x = currX;
y = currY;
}
void sort()
{
x = head;
int i = 0, j = 0;
for (i = 1; i < k; i++)
{
y = x->next;
for (j = i + 1; j <= k; j++)
{
if (x->data > y->data)
{
swap_node(i, j);
}
y = y->next;
}
x = x->next;
}
}
void print_node()
{
printf("------------Printing Node--------------\n");
node *temp = head;
do
{
printf("%d\n", temp->data);
temp = temp->next;
} while (temp != NULL);
}
void main(void)
{
int choice;
printf("MENU\n1-PUSH\n2-Print node\n");
do
{
printf("Enter Your Choice:");
scanf("%d", &choice);
switch (choice)
{
case 1:
push();
break;
case 2:
sort();
print_node();
break;
default:
printf("Wrong Choice!");
}
} while (choice == 1);
}