gpt4 book ai didi

c - 如何让链表的最后一个节点参与冒泡排序?

转载 作者:太空宇宙 更新时间:2023-11-04 07:54:15 25 4
gpt4 key购买 nike

我写了一个链表程序,我应该编写一个冒泡排序功能,但是最后一个节点似乎不参与冒泡排序。我猜那是因为指针移动到 NULL 并拒绝了最后一个节点数据。您能否建议我以任何其他方式对链表进行排序的方法,这也会有所帮助。

我的代码是:

#include<stdio.h>
#include<stdlib.h>
typedef struct node_type{
int data;
struct node_type *next;
}node;

typedef node *list;
list head;

void traverse()
{
list temp;
temp=head;
printf("\nThe Data is: \n");
while(temp!=NULL)
{
printf("%d\n",temp->data);
temp=temp->next;
}
printf("\n\n");
}

void sort_list()
{
list new,ptr;
int temp;
for(new=head;new->next!=NULL;new=new->next)
{
for(ptr=new->next;ptr->next!=NULL;ptr=ptr->next)
{
if(new->data > ptr->data)
{
temp=new->data;
new->data=ptr->data;
ptr->data=temp;
}
}
}
traverse();
}

void main()
{
list temp,new;
head=NULL;
int n;
char ch;
temp=(list) malloc(sizeof(node));
printf("\nGive data: ");
scanf("%d",&temp->data);
head=temp;
printf("\n");
printf("Enter more data(y/n): ");
scanf("\n%c",&ch);
while(ch=='y')
{
new=(list) malloc(sizeof(node));
printf("Give data: ");
scanf("%d",&new->data);
temp->next=new;
temp=new;
printf("\nEnter more data(y/n): ");
scanf("\n%c",&ch);
}
temp->next=NULL;
traverse(head);
printf("\n\nDo you want to sort the Link-List(y/n): ");
scanf("\n%c",&ch);
if(ch=='y')
{
sort_list();
}
}

输入:2 3 1 5 4

输出:1 2 3 5 4

最佳答案

sort_list()的内循环由于条件ptr->next!=NULL,在排序期间不考虑最后一个节点在for环形。你应该检查一下ptrNULL :

for(ptr = new->next; ptr != NULL; ptr = ptr->next)
^^^^

关于c - 如何让链表的最后一个节点参与冒泡排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51462004/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com