冒泡排序(链表版)

#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;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值