#include<stdio.h>
#include<stdlib.h>
typedef struct _node{
int value;
struct _node* next;
}Node;
Node* create();
void printlist(Node** head);
void destory(Node** head);
void Bubble(Node** head);
int lenlist(Node** head);
int main()
{
Node* a=create();
Bubble(&a);
printlist(&a);
destory(&a);
return 0;
}
Node* create()
{
Node* head=NULL;
int number;
do{
scanf("%d",&number);
if(number!=-1)
{
Node* p=(Node*)malloc(sizeof(Node));
p->next=NULL;
p->value=number;
Node* last=head;
if(last){
while(last->next){
last=last->next;
}
last->next=p;
}else{
head=p;
}
}
}while(number!=-1);
return head;
}
void printlist(Node** head)
{
Node* p=*head;
while(p)
{
printf("%d",p->value);
if(p->next){
printf(" ");
}else{
printf("\n");
}
p=p->next;
}
}
int lenlist(Node** head)
{
Node* p=*head;
int cnt=0;
while(p)
{
cnt++;
p=p->next;
}
return cnt;
}
void Bubble(Node** head)
{
Node* aPtr,*bPtr,*previous;//previous相当于是一个遍历指针,如同常常在for循环中使用的i一样,为计数器
int ischange=0;
int n=lenlist(head);
for(int i=1;i<n;i++)
{
ischange=0;
aPtr=*head;
previous=NULL;
bPtr=aPtr->next;
for(int j=0;j<n-i;j++)
{
if(!previous)//如果前面是零
{
if((aPtr->value)>(bPtr->value))
{
*head=bPtr;
//没有这一句 previous=aPtr->next;
//漏了这一句
aPtr->next=bPtr->next;
bPtr->next=aPtr;
ischange=1;
}
if(ischange==1)
{
//不对aPtr->next=bPtr->next;
bPtr=aPtr->next;//保持A在前
ischange=0;
}
else
{
aPtr=aPtr->next;
bPtr=bPtr->next;
}
//容易落下
previous=*head;//指向链表入口
}
else
{
//Node* temp=NULL;
if((aPtr->value)>(bPtr->value))
{
// temp=bPtr->next;
// previous->next=bPtr;
// bPtr->next=aPtr;
// aPtr->next=temp;
// ischange=1;
ischange=1;
aPtr->next=bPtr->next;
previous->next=bPtr;
bPtr->next=aPtr;
}
if(ischange==1)
{
ischange=0;
bPtr=aPtr->next;
previous=previous->next;
//错误previous->next=aPtr;
aPtr=previous->next;//容易落下的一行
}
else
{
aPtr=aPtr->next;
bPtr=bPtr->next;
previous=previous->next;
}
}
}
}
}
void destory(Node** head)
{
Node* p=*head;
Node* q=NULL;
while(p)
{
q=p;
p=p->next;
free(q);
}
*head=NULL;
}
冒泡排序(链表版)
最新推荐文章于 2023-06-06 23:49:13 发布