题目
在链式存储结构上设计冒泡排序算法
代码
// 链式存储结构实现冒泡排序
#include <iostream>
using namespace std;
typedef struct LNode{
int data;
struct LNode *next;
}LNode,*LinkList;
void createLinkList(LinkList &L){
L=(LNode *)malloc(sizeof(LNode));
LNode *p,*r=L;
int e;
cin>>e;
while(e!=999){
p=(LNode *)malloc(sizeof(LNode));
p->data=e;
r->next=p;
r=p;
cin>>e;
}
r->next=NULL;
}
void dispLinkList(LinkList L){
LNode *p=L->next;
while(p){
cout<<p->data<<" ";
p=p->next;
}
cout<<endl;
}
int getLinkListLength(LinkList L){
LNode *p=L->next;
int length=0;
while(p){
length++;
p=p->next;
}
return length;
}
//链式存储结构的冒泡排序
void BubbleSort(LinkList &L){
if(L->next==NULL)
return;
int len=getLinkListLength(L);
LNode *p,*q;
for(int i=0;i<len;i++,len--){
//每一趟排序都会确定一个最终位置
p=L->next;
int j=0;
while(p!=NULL&&j<len){
q=p->next;
if(q!=NULL&&p->data>q->data){
swap(q->data,p->data);
}
j++;
p=p->next;
}
}
}
int main() {
LinkList L;
createLinkList(L);
dispLinkList(L);
cout<<getLinkListLength(L);
BubbleSort(L);
cout<<endl;
dispLinkList(L);
return 0;
}