c - 我应该怎么做才能使链表中的最后一个节点参与冒泡排序?
问题描述
我写了一个链表程序,我应该编写一个冒泡排序功能,但是最后一个节点似乎没有参与冒泡排序。我猜那是因为指针移动到 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
ptr
NULL
for(ptr = new->next; ptr != NULL; ptr = ptr->next)
^^^^
推荐阅读
- pytorch - PyTorch python 与 C++ 的绑定在哪里?
- python - Wagtail:动态选择具有默认值的模板
- sql - 错误 tcNull Golang HanadB
- scikit-learn - 潜在语义分析:如何选择组件号来执行截断SVD
- python - 绘制共享 x 值的三个函数
- linux - 如何在linux中的给定时间关闭firefox?
- javascript - react-native 构建错误(开发服务器返回响应错误代码:500)
- ios - 使用 Kingfisher 取消单个图像下载
- sql - 指定两个排序索引?
- email - Google Analytics(分析)测量协议命中 URL 中的 Mailchimp 合并标签