C语言 通过交换节点选择单链表(迭代方法)?



>我正在尝试通过交换节点本身对单向链表执行选择排序,但在所有输入之后,看起来我的sort((函数无法正常工作。 我错过了什么或做错了什么,请有人帮助我。

注意:所有函数和指针的名称几乎都说明了他们的任务,所以我想不要添加评论,但如果有人想要评论,请告诉我。

注意:在swap_node(int i, int j)中,ij是需要交换的两个节点的位置。

#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("%dn", temp->data);
temp = temp->next;
} while (temp != NULL);
}
void main(void)
{
int choice;
printf("MENUn1-PUSHn2-Print noden");
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);
}

为什么不直接交换内容:

void swap_content (node *first, node *second) {
int med = first->data; 
first->data = second->data;
second->data = med;
}

相关内容

  • 没有找到相关文章

最新更新