您的位置:首页 > 其它

采用单链表进行冒泡排序

2015-03-27 20:21 211 查看
#include <stdio.h>
#include <stdlib.h>

typedef struct Node{

struct Node *next;
int num;
}Node;

void bubble_sort(Node* head)
{
Node* tail = NULL;
while(tail != head->next)
{
Node* pre = head;
Node* cur = pre->next;
while(cur != tail && cur->next != tail)
{
if( cur->num > cur->next->num )
{
//交换当前节点和后一个节点
pre->next = cur->next;
cur->next = cur->next->next;
pre->next->next = cur;
}
pre = pre->next;
cur = pre->next;
}
tail = cur;
}
}

void main()
{
int num;
Node *head;
Node *pre,*p;
head = (Node *)malloc(sizeof(Node));
pre = head;
printf("输入整型数据,以字母q(Q)结尾\n");
while(scanf("%d",&num)!=NULL&& (num !=(int)'q' || num!='Q'))
{
p = (Node *)malloc(sizeof(Node));
p->num=num;
pre->next = p;
pre = p;

}
p->next=NULL;
bubble_sort(head);
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: